Complete Docker Commands Cheat Sheet

Docker is a powerful platform for containerizing applications, making it easier to deploy, manage, and scale. This in-depth cheat sheet covers everything you need to know about Docker, from essential commands to Dockerfile syntax, volumes, networking, Docker Compose, and security best practices.

Essential Docker Commands

Docker provides various commands to manage containers, images, networks, and volumes. Below are the most commonly used Docker commands, along with examples.

Starting and Stopping Containers:

  • Run a container: Starts a container in detached mode.
    docker run -d --name container_name image_name
  • Run a container with port mapping: Map port 80 in the container to port 8080 on the host.
    docker run -d -p 8080:80 --name web_server nginx
  • Stop a container: Gracefully stops a running container.
    docker stop container_name
  • Forcefully stop a container: Kills a container immediately.
    docker kill container_name
  • Restart a container: Stops and starts a container.
    docker restart container_name
  • Remove a container: Removes a stopped container.
    docker rm container_name
  • List running containers: Shows all currently running containers.
    docker ps
  • List all containers (including stopped ones):
    docker ps -a

Working with Docker Images:

  • List available images: Shows all downloaded Docker images.
    docker images
  • Pull an image from Docker Hub: Downloads an image from Docker Hub to your local system.
    docker pull image_name:tag
  • Remove an image: Deletes a Docker image from your local system.
    docker rmi image_name
  • Tag an image: Assign a new tag to an existing image.
    docker tag image_name:tag new_image_name:new_tag
  • Inspect an image: Display detailed information about an image.
    docker inspect image_name

Docker Container Logging and Stats:

  • View container logs: Shows logs for a specific container.
    docker logs container_name
  • Stream live logs: Continuously displays logs from a running container.
    docker logs -f container_name
  • Monitor container resource usage: Displays real-time CPU, memory, network, and disk I/O statistics for running containers.
    docker stats

Dockerfile Syntax and Instructions

The Dockerfile is a text document that contains a series of instructions used to build a Docker image. Each instruction creates a layer in the image, forming a lightweight, portable application stack.

Key Dockerfile Instructions:

  • FROM: Defines the base image for the Docker image.
    FROM ubuntu:latest
  • RUN: Executes commands in the container during the build process.
    RUN apt-get update && apt-get install -y nginx
  • WORKDIR: Sets the working directory inside the container.
    WORKDIR /app
  • COPY: Copies files from the host to the container.
    COPY ./src /app/src
  • CMD: Specifies the default command to run inside the container.
    CMD ["npm", "start"]
  • ENTRYPOINT: Defines the main process that will run in the container.
    ENTRYPOINT ["./entrypoint.sh"]
  • EXPOSE: Informs Docker that the container will listen on a specific port at runtime.
    EXPOSE 80
  • ENV: Sets environment variables inside the container.
    ENV NODE_ENV=production

Example Dockerfile for a Node.js Application:

FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

Best Practices for Dockerfile:

  • Minimize Layers: Use fewer RUN instructions by chaining commands to reduce the number of layers.
    RUN apt-get update && apt-get install -y package1 package2
  • Use Multi-Stage Builds: Split your Dockerfile into multiple stages to reduce the final image size.
    FROM node:14 as build
    WORKDIR /app
    COPY . .
    RUN npm install && npm run build
    
    FROM nginx:alpine
    COPY --from=build /app/build /usr/share/nginx/html
  • Order Matters: Place the most frequently changing instructions (like COPY) at the bottom to improve Docker layer caching.

Managing Volumes

Docker volumes are used to persist data between container restarts and across different containers. Volumes provide a way to store data externally from the container's filesystem, allowing it to be shared between multiple containers or preserved after a container is removed.

Working with Volumes:

  • Create a volume: Creates a named volume.
    docker volume create my_volume
  • Mount a volume to a container: Mounts the volume inside a container at the specified path.
    docker run -d -v my_volume:/app/data my_image
  • Bind Mount: Mounts a host directory to a container. Useful for development environments.
    docker run -v /path/on/host:/path/in/container my_image
  • List volumes: Displays a list of all Docker volumes.
    docker volume ls
  • Remove a volume: Deletes a volume.
    docker volume rm volume_name
  • Inspect a volume: Shows detailed information about a volume.
    docker volume inspect volume_name

Networking in Docker

Docker networking allows containers to communicate with each other, the host machine, and external networks. Docker provides several network modes, each with different use cases.

Docker Networking Commands:

  • Create a network: Defines a new Docker network.
    docker network create my_network
  • Connect a container to a network: Adds a running container to an existing network.
    docker network connect my_network my_container
  • Disconnect a container from a network: Removes a container from a network.
    docker network disconnect my_network my_container
  • Inspect a network: Displays detailed information about a network.
    docker network inspect my_network

Docker Network Modes:

  • Bridge (default): Isolated network where containers can communicate with each other and access external networks through the host.
  • Host: Shares the host’s network stack, allowing the container to use the host's IP and ports.
  • None: Disables all networking for the container.

Docker Compose for Multi-Container Applications

Docker Compose is a tool that simplifies the management of multi-container Docker applications. Using a docker-compose.yml file, you can define services, networks, and volumes, and easily orchestrate their execution.

Key Docker Compose Commands:

  • Start services: Starts all services defined in the docker-compose.yml file.
    docker-compose up
  • Start services in detached mode: Runs services in the background.
    docker-compose up -d
  • Stop services: Stops all running services.
    docker-compose down
  • Rebuild images: Rebuilds the service images without cache.
    docker-compose build --no-cache

Example docker-compose.yml File:

version: '3'
services:
  web:
    image: nginx:alpine
    ports:
      - "8080:80"
    volumes:
      - ./html:/usr/share/nginx/html
  app:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - db
  db:
    image: postgres
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: app_db

Security in Docker

Ensuring container security is a critical part of any Docker workflow. Below are some best practices and key security features for working with Docker containers.

Security Best Practices for Docker:

  • Run containers as non-root users: Avoid running containers as root to minimize the risk of privilege escalation attacks.
    USER nonrootuser
  • Use signed images: Always pull signed and trusted images from Docker Hub or your internal registry to prevent tampering.
    docker pull --disable-content-trust=false image_name
  • Limit container capabilities: Restrict the capabilities granted to containers using --cap-drop and --cap-add.
    docker run --cap-drop=ALL --cap-add=NET_ADMIN my_image
  • Scan images for vulnerabilities: Regularly scan your images for security vulnerabilities using tools like Clair or Trivy.
  • Set resource limits: Use --memory and --cpus flags to set limits on memory and CPU usage to prevent containers from exhausting host resources.
    docker run --memory="500m" --cpus="1" my_image

Best Practices

Following Docker best practices ensures that your containers and images are optimized for performance, security, and maintainability. Below are some general guidelines.

General Docker Best Practices:

  • Use lightweight base images: Choose small base images like alpine or scratch to minimize image size and attack surface.
    FROM alpine
  • Minimize layers: Chain commands together to reduce the number of layers in your Docker image.
    RUN apt-get update && apt-get install -y package1 package2
  • Remove unnecessary files: Clean up temporary files and caches after installing packages to reduce image size.
    RUN apt-get clean && rm -rf /var/lib/apt/lists/*
  • Tag your images: Use meaningful tags for your Docker images, such as version numbers or release dates.
    docker tag my_image:latest my_image:v1.0.0
  • Regularly update images: Keep your base images up to date to include the latest security patches.
    docker pull ubuntu:latest