Skip to content

Docker Container Management

Category: DevOps and System Tools
Type: Linux Commands
Generated on: 2025-07-10 03:18:35
For: System Administration, Development & Technical Interviews


Docker Container Management Cheatsheet (Linux Commands)

Section titled “Docker Container Management Cheatsheet (Linux Commands)”

This cheatsheet provides a practical guide to managing Docker containers using Linux commands, geared towards DevOps and System Administrators.

This section outlines the purpose of each command and when it is most useful.

  • docker run: Creates and starts a new container from an image. Use when you need to deploy a new application or service.
  • docker start: Starts a stopped container. Use when you need to bring a stopped service back online.
  • docker stop: Gracefully stops a running container. Use before making changes to the underlying system or when temporarily pausing a service.
  • docker kill: Forcefully stops a running container. Use when a container is unresponsive or needs immediate termination.
  • docker restart: Restarts a running or stopped container. Use when a service needs a quick refresh.
  • docker rm: Removes a stopped container. Use to clean up unused containers and free up resources. Warning: Data loss if not properly persisted.
  • docker ps: Lists running containers. Use to monitor container status and identify specific containers.
  • docker exec: Executes a command inside a running container. Use to troubleshoot, debug, or perform administrative tasks within a container.
  • docker logs: Fetches the logs of a container. Use to monitor application behavior, diagnose errors, and track events.
  • docker inspect: Displays detailed information about a container. Use to examine container configuration, network settings, and resource usage.
  • docker stats: Displays resource usage statistics of running containers. Use to monitor container performance and identify bottlenecks.
  • docker top: Displays the processes running inside a container. Use to understand the processes and resource consumption inside a specific container.
  • docker commit: Creates a new image from a container’s changes. Use to save modifications made within a container as a new reusable image.
  • docker cp: Copies files/folders between a container and the host machine. Use to transfer data in and out of containers.
  • docker attach: Attaches to a running container. Use to interact directly with the main process of the container.

This section shows the command structure and common options.

Terminal window
docker <command> [options] <arguments>

Common Options:

  • -d, --detach: Run the container in the background (detached mode).
  • -i, --interactive: Keep STDIN open even if not attached.
  • -t, --tty: Allocate a pseudo-TTY.
  • -p, --publish: Publish a container’s port(s) to the host. host_port:container_port
  • -v, --volume: Bind mount a volume. host_path:container_path
  • -e, --env: Set environment variables. VARIABLE=value
  • --name: Assign a name to the container.
  • --rm: Automatically remove the container when it exits (useful for ephemeral containers).
  • --network: Connect the container to a network.
  • --privileged: Give extended privileges to this container. Use with caution.

This section demonstrates real-world usage scenarios.

  • Running a basic web server:
Terminal window
docker run -d -p 80:80 --name webserver nginx
This command pulls the `nginx` image, runs it in detached mode, maps port 80 on the host to port 80 in the container, and names the container `webserver`.
  • Running a container with environment variables:
Terminal window
docker run -d -e "DATABASE_URL=postgres://user:password@host:port/database" my-app
This command runs the `my-app` image in detached mode and sets the `DATABASE_URL` environment variable.
  • Running a container with a volume mount:
Terminal window
docker run -d -v /host/data:/container/data --name data-container my-image
This command runs the `my-image` image in detached mode and mounts the `/host/data` directory on the host to the `/container/data` directory in the container. Any changes made to files in `/container/data` inside the container will be reflected in `/host/data` on the host, and vice versa.
  • Listing running containers:
Terminal window
docker ps
This command lists all running containers, showing their container ID, image, command, created time, status, ports, and names.
Example Output:
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a1b2c3d4e5f6 nginx "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:80->80/tcp webserver
```
  • Listing all containers (running and stopped):
Terminal window
docker ps -a
  • Stopping a container:
Terminal window
docker stop webserver
This command stops the container named `webserver`.
  • Killing a container:
Terminal window
docker kill webserver
This command forcefully stops the container named `webserver`.
  • Removing a container:
Terminal window
docker rm webserver
This command removes the container named `webserver`. **Warning: Data will be lost if not persisted.**
  • Executing a command inside a container:
Terminal window
docker exec -it webserver bash
This command executes a bash shell inside the `webserver` container, allowing you to interact with the container.
  • Viewing container logs:
Terminal window
docker logs webserver
This command displays the logs of the `webserver` container.
  • Viewing container logs in real-time (follow):
Terminal window
docker logs -f webserver
  • Inspecting a container:
Terminal window
docker inspect webserver
This command displays detailed information about the `webserver` container in JSON format.
  • Copying a file from the host to a container:
Terminal window
docker cp /host/file.txt webserver:/container/file.txt
  • Copying a file from a container to the host:
Terminal window
docker cp webserver:/container/file.txt /host/file.txt
  • Creating an image from a container:
Terminal window
docker commit webserver my-new-image:1.0
This command creates a new image named `my-new-image` with tag `1.0` based on the current state of the `webserver` container.
  • Getting resource statistics of a container:
Terminal window
docker stats webserver
This command shows live CPU, memory, network, and I/O usage for the `webserver` container.
  • Viewing processes running inside a container:
Terminal window
docker top webserver
This command lists the processes running inside the `webserver` container, similar to the `top` command on a Linux system.
  • Attaching to a running container:
Terminal window
docker attach webserver
This command attaches your terminal to the main process running in the `webserver` container. Press `Ctrl+C` or `Ctrl+P Ctrl+Q` to detach without stopping the container.

This section provides details on the most useful flags and parameters.

  • -d, --detach: Run the container in the background. Useful for long-running services.
  • -i, --interactive: Keep STDIN open even if not attached. Often used with -t.
  • -t, --tty: Allocate a pseudo-TTY. Creates an interactive terminal session. Often used with -i.
  • -p, --publish: Publish a container’s port(s) to the host.
    • 80:80: Maps host port 80 to container port 80.
    • 8080:80: Maps host port 8080 to container port 80.
    • 127.0.0.1:80:80: Maps host port 80 on localhost to container port 80.
  • -v, --volume: Bind mount a volume.
    • /host/data:/container/data: Binds the host directory /host/data to the container directory /container/data.
    • my-volume:/container/data: Mounts a named volume my-volume to the container directory /container/data. Docker manages the volume’s storage location.
  • -e, --env: Set environment variables.
    • DATABASE_URL=postgres://user:password@host:port/database: Sets the DATABASE_URL environment variable.
  • --name: Assign a name to the container. Makes it easier to refer to the container.
  • --rm: Automatically remove the container when it exits. Useful for short-lived containers.
  • --network: Connect the container to a network.
    • --network host: Uses the host’s network stack (not recommended for security reasons unless absolutely necessary).
  • --privileged: Give extended privileges to this container. Use with extreme caution. This can expose the host system to security risks. Generally, avoid this unless absolutely necessary and you fully understand the implications.
  • --user: Specifies the user ID or username to run the container process as. Useful for security. Example: --user 1000:1000 or --user myuser.
  • --entrypoint: Overrides the default entrypoint of the image. Example: --entrypoint /bin/sh.

This section explores complex examples and combinations.

  • Running a container with multiple port mappings and volumes:
Terminal window
docker run -d -p 80:80 -p 443:443 -v /host/web:/var/www/html -v /host/logs:/var/log/nginx --name webapp nginx
This command runs an `nginx` container in detached mode, maps ports 80 and 443, mounts two volumes, and names the container `webapp`.
  • Using docker exec to run a script inside a container:
Terminal window
docker exec webserver /path/to/my/script.sh
This command executes the `script.sh` script inside the `webserver` container.
  • Chaining commands with docker exec:
Terminal window
docker exec -it webserver bash -c "apt-get update && apt-get install -y some-package"
This command executes multiple commands sequentially inside the `webserver` container.
  • Creating a container with resource limits:
Terminal window
docker run -d --memory 1g --cpu-shares 512 --name limited-container my-image
This command runs the `my-image` container with a memory limit of 1GB and CPU shares of 512. Useful for preventing resource exhaustion.
  • Using named volumes for persistent data:
Terminal window
docker volume create my-data
docker run -d -v my-data:/app/data --name my-app my-image
This creates a named volume `my-data` and mounts it to `/app/data` inside the `my-app` container. Data in this volume will persist even if the container is removed.
  • Running a container that depends on another container (linking):

This is deprecated; use Docker networks instead. Example shown for informational purposes only.

```bash
docker run -d --name db postgres
docker run -d --name app --link db:db my-app
```
This runs a `postgres` database container and then runs the `my-app` container, linking it to the `db` container. The `app` container can access the `db` container using the hostname `db`.
  • Using Docker networks for container communication (recommended):
Terminal window
docker network create my-network
docker run -d --name db --network my-network postgres
docker run -d --name app --network my-network my-app
This creates a Docker network named `my-network` and connects both the `db` and `app` containers to it. The `app` container can access the `db` container using its container name (`db`) as a hostname.

This section provides pro tips and shortcuts.

  • Use container names instead of IDs: Names are much easier to remember and use.
  • Use named volumes for persistent data: This makes managing persistent data much easier.
  • Combine commands for efficiency: Use shell scripting or docker exec -it <container> bash -c "command1 && command2" to execute multiple commands at once.
  • Use the --rm flag for ephemeral containers: This automatically cleans up containers after they exit.
  • Create aliases for frequently used commands: For example, alias dps='docker ps'
  • Use docker history <image> to see the layers of an image: This helps understand the size and composition of the image.
  • Utilize Docker Compose for multi-container applications: Define and manage multiple containers as a single application.
  • Use a .dockerignore file: Exclude unnecessary files and directories from the build context to speed up image builds and reduce image size.
  • Keep your Dockerfiles concise and efficient: Use multi-stage builds to reduce image size.

This section covers common errors and solutions.

  • Port already in use: Error message: Error starting userland proxy: listen tcp 0.0.0.0:80: bind: address already in use.

    • Solution: Stop the process using the port on the host machine or change the port mapping in the docker run command. Use netstat -tulnp or ss -tulnp to find the process using the port.
  • Container fails to start: Check the container logs using docker logs <container_name> to identify the error.

  • Cannot connect to a container: Ensure the container is running and the correct ports are mapped. Check firewall rules on the host machine.

  • Permission denied errors: Ensure the user running the docker command has the necessary permissions. Check volume mount permissions. You might need to adjust user IDs using the --user flag in docker run.

  • “No space left on device” error: This can occur if the Docker daemon has run out of disk space. Prune unused images, containers, and volumes using docker system prune -a.

  • Container exits immediately: Check the container logs (docker logs <container_name>) to understand why the container exited. The main process might have crashed or exited.

  • “Error response from daemon: conflict: …”: This usually means a container with the same name is already running or exists. Stop and remove the existing container before starting a new one with the same name.

  • Slow container performance: Check resource usage using docker stats. Increase resource limits if necessary. Optimize the application running inside the container. Use faster storage for volumes.

This section lists connected commands and alternatives.

  • docker image: Manages Docker images.
  • docker network: Manages Docker networks.
  • docker volume: Manages Docker volumes.
  • docker compose: Defines and runs multi-container applications.
  • docker build: Builds a Docker image from a Dockerfile.
  • docker login: Logs in to a Docker registry.
  • docker push: Pushes an image to a Docker registry.
  • docker pull: Pulls an image from a Docker registry.
  • docker system prune: Removes unused data.
  • docker swarm: Manages a Docker Swarm cluster.
  • kubectl: Kubernetes command-line tool (for container orchestration).

This cheatsheet provides a comprehensive overview of Docker container management commands. Remember to consult the official Docker documentation for the most up-to-date information and advanced features. Remember to adapt these examples to your specific needs and always test thoroughly before deploying to production.