Skip to main content

Running and Managing Containers

1. Running Containers

Command Description Options Example
docker run Creates and starts a new container from an image -d, -p, -v, --name docker run -d -p 8080:80 --name my-app nginx
docker start Starts a stopped container --attach, -i docker start my-container
docker stop Stops a running container gracefully -t (timeout in seconds) docker stop -t 10 my-container
docker restart Restarts a running or stopped container -t (timeout in seconds) docker restart -t 5 my-container
docker exec Execute a command inside a running container -it, --user docker exec -it my-container /bin/bash

Example: Running a Web Server Container

docker run -d --name web-server -p 80:80 nginx

Example: Starting a Container with Custom Volume Mounting

docker run -d --name app-container -v /host/data:/container/data node:18
Note: The -d flag runs the container in detached mode, meaning it runs in the background.
Warning: When using docker run, if no image is specified, Docker will pull from Docker Hub by default.

2. Running in Detached Mode

Running containers in detached mode allows them to run in the background without blocking your terminal.

Option Description Example
-d, --detach Run container in detached mode docker run -d --name myapp nginx

Example: Running a Web Server in Detached Mode

docker run -d --name webserver -p 8080:80 nginx
Note: The container continues running in the background until explicitly stopped or removed.

Key Points

  • Use -d flag to run containers in detached mode.
  • Container logs can be viewed using docker logs.
  • Detached containers are useful for long-running services like web servers.

3. Running Interactive Containers

Command Description Example
docker run -it Run a container interactively with a TTY docker run -it ubuntu:20.04 /bin/bash
docker exec -it Execute a command in a running container interactively docker exec -it container_name /bin/sh

Example: Running an Interactive Bash Shell

docker run -it --name my_container ubuntu:20.04 /bin/bash
Note: The -it flags are essential for interactive mode: -i keeps STDIN open and -t allocates a pseudo-TTY.

Key Points

  • -it enables interactive terminal session
  • Use docker exec to enter a running container
  • Common use case: debugging or exploring container contents

4. Naming Containers

Option Values Description
--name container-name Name to assign to the container
--hostname container-hostname Set the hostname inside the container

Example: Naming a Container

docker run --name my-app-container nginx
Note: Container names must be unique; reusing a name will cause an error unless you remove the existing container first.

5. Removing Containers After Exit

Command Description Notes
docker container prune Remove all stopped containers Use with caution; removes all unused containers
docker container rm <container-id> Remove a specific stopped container Container must be stopped before removal
docker container rm -f <container-id> Force remove a running container Stops and removes the container immediately

Example: Remove a stopped container

docker container rm my-container

Example: Remove all stopped containers

docker container prune
Note: Use docker container ls -a to list all containers including stopped ones before removal.
Warning: Force removing a running container with -f will not allow graceful shutdown and may lead to data loss.

6. Overriding Container Commands

Command Description Example
docker run Runs a new container with overridden command docker run ubuntu echo "Hello World"
docker exec Executes a command in a running container docker exec -it container_name ps aux

Example: Override command on container run

docker run ubuntu echo "Hello from Docker"

Example: Execute command in running container

docker exec -it my_container ls -l
Note: The docker run command overrides the default entrypoint of the image, while docker exec runs a command in a running container.

7. Running Containers as Different User

Option Values Notes
--user uid[:gid] Run container as specified user ID and group ID
--user username[:groupname] Run container as specified user and group by name

Example: Running container as non-root user

docker run --user 1000:1000 ubuntu whoami

Example: Running container with user by name

docker run --user node:node ubuntu whoami
Note: User must exist in the container image or be created at runtime.
Warning: Running as root inside container can still pose security risks even if host is non-root.

8. Mapping Ports

Option Description Example
-p Map a container port to a host port docker run -p 8080:80 nginx
-P Expose all published ports to random host ports docker run -P nginx
--publish Long form of -p docker run --publish 8080:80 nginx

Example: Map a single port

docker run -p 8080:80 nginx

Example: Map multiple ports

docker run -p 8080:80 -p 443:443 nginx

Example: Map port with random host port

docker run -P nginx
Note: The format is hostPort:containerPort. If only the container port is specified, Docker assigns a random host port.

9. Setting Environment Variables

Method Description Example
-e Set a single environment variable docker run -e NODE_ENV=production myapp
--env-file Load environment variables from a file docker run --env-file .env myapp
ENV in Dockerfile Set environment variables during image build ENV DATABASE_URL=postgresql://localhost:5432/mydb

Example: Using environment variables in a Node.js app

const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
Note: Environment variables set with -e override values from --env-file.
Warning: Never commit sensitive credentials (e.g. API keys) into Dockerfiles or public repositories.

10. Mounting Volumes

Option Description Example
-v Mount a volume (short form) docker run -v /host/path:/container/path image
--mount Mount a volume (long form) docker run --mount type=bind,source=/host/path,target=/container/path image
-v /host/path:/container/path:ro Read-only volume mount docker run -v /home/user/data:/app/data:ro image

Example: Mounting a Host Directory

docker run -d \
  --name myapp \
  -v /home/user/app:/usr/src/app \
  node:18

Example: Using Named Volumes

docker volume create mydata
docker run -d \
  --name db \
  -v mydata:/var/lib/mysql \
  mysql:8.0
Note: Named volumes are managed by Docker and are safer for data persistence.
Warning: Ensure proper file permissions on host directories to avoid container access issues.

11. Limiting Container Resources

Resource Flag/Option Description Example
Memory --memory Set maximum memory usage for container docker run --memory=512m ubuntu
CPU --cpus Limit CPU usage to a specific number of cores docker run --cpus=1.5 ubuntu
Memory Swap --memory-swap Set total memory + swap limit docker run --memory-swap=1g ubuntu
Memory Reservation --memory-reservation Set memory reservation (soft limit) docker run --memory-reservation=256m ubuntu
CPU Shares --cpu-shares Set relative CPU shares (default 1024) docker run --cpu-shares=512 ubuntu

Example: Limiting Memory and CPU

docker run --memory=1g --cpus=0.5 ubuntu
Note: Resource limits are enforced by the Linux kernel's cgroup subsystem. Setting limits below 6MB may cause issues.

12. Restarting Containers Automatically

Option Values Description
--restart no, on-failure[:max-retries], unless-stopped, always Restart policy for the container

Example: Setting Restart Policy

docker run --restart=always nginx
docker run --restart=unless-stopped redis
docker run --restart=on-failure:5 mysql
Note: The unless-stopped policy restarts the container unless it was explicitly stopped by the user or the host system.

Was this article helpful?