Quick take: Docker has revolutionized the way we build, ship, and run applications across different environments.

Essential Docker Commands Every Engineer Should Know

Docker has revolutionized the way we build, ship, and run applications across different environments. Whether you are a seasoned DevOps engineer or just beginning your containerization journey, understanding the core Docker commands is fundamental to your success. This comprehensive guide covers every essential Docker command you need to master, organized by category with practical examples that you can implement immediately in your infrastructure.

Docker commands form the backbone of container management, enabling you to orchestrate entire application stacks with simple terminal instructions. From creating and managing images to networking containers and monitoring their performance, these commands provide complete control over your containerized environments. Let us explore each category in depth so you can build robust, production-ready container solutions.

Understanding Docker Command Structure

Basic Docker Command Syntax

Every Docker command follows a predictable pattern that makes learning and remembering them straightforward. The basic syntax is:

docker [OPTIONS] COMMAND [ARG...]

The OPTIONS modify how Docker executes the command, COMMAND specifies what action to perform, and ARG provides additional parameters for that command. Most Docker commands support the --help flag which displays detailed information about the command and its available options.

Docker organizes commands into logical groups such as image commands, container commands, network commands, and volume commands. Understanding this organization helps you quickly locate the command you need and understand its purpose within the Docker ecosystem.

Getting Help and Version Information

Before diving into specific commands, you should know how to access Docker documentation directly from your terminal. These commands provide immediate assistance:

docker --version
docker --help
docker COMMAND --help

The docker --version command displays your current Docker installation version, which is essential when troubleshooting compatibility issues. The docker --help command lists all available commands, while docker COMMAND --help provides detailed information about a specific command, including all available flags and options.

Essential Image Commands

Pulling Images from Docker Registry

Before you can run a container, you need to have an image available on your system. The docker pull command downloads images from Docker registries, most commonly Docker Hub:

docker pull ubuntu:22.04
docker pull nginx:latest
docker pull python:3.11-slim
docker pull myregistry.azurecr.io/myapp:v1.0.0

The image name follows the format registry/repository:tag. If you omit the registry, Docker assumes Docker Hub. If you omit the tag, Docker uses latest by default. The latest tag does not guarantee the most recent version, so always specify explicit version tags in production environments for reproducibility.

You can pull multiple images efficiently by creating a script that pulls all dependencies for your application stack. This is particularly useful when setting up new servers or CI/CD pipelines:

#!/bin/bash
IMAGES=("nginx:1.25" "postgres:15" "redis:7-alpine")
for image in "${IMAGES[@]}"; do
  docker pull "$image"
done

Listing Available Images

The docker images command displays all images stored on your system, along with useful metadata:

docker images
docker images --filter "dangling=true"
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
docker images ubuntu

The first command lists all images with default formatting showing repository, tag, image ID, creation time, and size. The second command finds dangling images (images without tags that are no longer needed), which is useful for cleanup operations. The third command demonstrates custom formatting using Go templates, allowing you to display only the information you need. The fourth command filters images by repository name.

Finding large images in your system helps optimize storage and network bandwidth:

docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" | sort -k3 -h

Building Custom Images

The docker build command creates custom images from a Dockerfile. This is one of the most important commands in your Docker workflow:

docker build -t myapp:1.0.0 .
docker build -t myregistry.azurecr.io/myapp:v1.0.0 -f Dockerfile.prod .
docker build --build-arg VERSION=1.0.0 -t myapp:1.0.0 .
docker build -t myapp:latest --no-cache .

The -t flag tags the image with a repository and version. The -f flag specifies an alternative Dockerfile when you have multiple build configurations. The --build-arg flag passes build-time variables to the Dockerfile, enabling dynamic builds for different environments. The --no-cache flag forces Docker to rebuild each layer instead of using cached versions, ensuring a fresh build.

Creating an efficient Dockerfile for building a Python application demonstrates best practices:

cat > Dockerfile << 'EOF'
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]
EOF

Then build and tag the image:

docker build -t myapp:1.0.0 .
docker tag myapp:1.0.0 myapp:latest

Inspecting Image Details

The docker inspect command provides detailed metadata about an image in JSON format:

docker inspect nginx:latest
docker inspect --format='{{.Config.Cmd}}' nginx:latest
docker inspect --format='{{json .Config.Env}}' ubuntu:22.04 | jq .

The first command displays all available information about the image. The second command extracts just the default command that runs when the container starts. The third command retrieves environment variables in JSON format and pipes them to jq for pretty-printing.

Removing Images

Cleaning up unused images saves disk space and keeps your system organized:

docker rmi ubuntu:22.04
docker rmi image_id_1 image_id_2 image_id_3
docker image prune
docker image prune -a
docker image prune --filter "until=240h"

The docker rmi command removes one or more images by name or ID. The docker image prune command removes all dangling images (images with no tags or containers using them). The -a flag removes all unused images. The --filter option allows you to remove images older than a specified duration, useful for automated cleanup in CI/CD pipelines.

Core Container Commands

Running Containers

The docker run command creates and starts a new container from an image. This is probably the most frequently used Docker command:

docker run -d --name webserver -p 8080:80 nginx:latest
docker run -it ubuntu:22.04 /bin/bash
docker run -e DATABASE_URL=postgres://db:5432/mydb myapp:1.0.0
docker run -v /host/path:/container/path -d myapp:latest
docker run --cpus="1.5" --memory="512m" myapp:latest

The first command runs nginx in detached mode (-d) in the background, names it webserver (--name), and maps port 8080 on the host to port 80 in the container (-p). The second command runs an interactive terminal session in an Ubuntu container. The third command sets environment variables with -e. The fourth command mounts a host directory inside the container using -v. The fifth command restricts resource consumption with CPU and memory limits.

A comprehensive example that demonstrates a production-ready container start:

docker run \
  --name app-prod \
  --restart unless-stopped \
  -d \
  -p 8080:3000 \
  -e NODE_ENV=production \
  -e LOG_LEVEL=info \
  -v /var/log/app:/app/logs \
  --cpus="2" \
  --memory="1g" \
  --health-cmd="curl -f http://localhost:3000/health || exit 1" \
  --health-interval=30s \
  --health-timeout=10s \
  --health-retries=3 \
  myapp:1.0.0

This example includes automatic restart policy, proper resource allocation, volume mounting for logs, health checks, and comprehensive environment configuration.

Listing Running Containers

The docker ps command shows all running containers:

docker ps
docker ps -a
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}"
docker ps -q

The first command lists only currently running containers. The -a flag shows all containers including stopped ones. The custom format option lets you display specific information. The -q flag outputs only container IDs, useful for scripting and bulk operations.

Executing Commands in Running Containers

The docker exec command runs commands inside running containers without stopping them:

docker exec webserver nginx -t
docker exec -it container_name /bin/bash
docker exec -u root container_name apt-get update
docker exec -e CUSTOM_VAR=value container_name env

The first command tests nginx configuration inside the webserver container. The second command opens an interactive bash session. The -u flag runs the command as a specific user, and the -e flag sets environment variables for that execution.

Viewing Container Logs

The docker logs command retrieves output from containers, essential for debugging:

docker logs container_name
docker logs -f container_name
docker logs --tail 50 container_name
docker logs --since 2024-01-15T10:00:00 container_name
docker logs --timestamps container_name

The first command displays all accumulated logs. The -f flag streams logs in real-time like tail -f. The --tail option limits output to the last specified number of lines. The --since flag shows logs from a specific time. The --timestamps flag includes timestamps with each log line.

Combining flags for advanced log analysis:

docker logs -f --timestamps container_name | grep ERROR

Stopping and Starting Containers

These commands manage the lifecycle of containers:

docker stop container_name
docker stop --time=30 container_name
docker start container_name
docker restart container_name
docker kill container_name

The docker stop command gracefully stops a container, sending SIGTERM signal. The --time flag sets how long Docker waits before force-killing the container. The docker start command restarts a stopped container. The docker restart command is equivalent to stop followed by start. The docker kill command immediately terminates the container with SIGKILL.

Removing Containers

Clean up containers you no longer need:

docker rm container_name
docker rm container_id_1 container_id_2
docker rm -f container_name
docker container prune
docker container prune --filter "until=24h"

The docker rm command removes stopped containers. The -f flag forcefully removes even running containers. The docker container prune command removes all stopped containers. The --filter option allows conditional removal based on time or other criteria.

Viewing Container Resource Usage

The docker stats command monitors real-time resource consumption:

docker stats
docker stats container_name
docker stats --no-stream
docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"

The first command shows live statistics for all running containers. The second command monitors a specific container. The --no-stream flag displays current stats once instead of continuously. The format option allows custom output formatting.

Image Registry Commands

Pushing Images to Registries

The docker push command uploads images to registries for sharing and deployment:

docker push myregistry.azurecr.io/myapp:1.0.0
docker push docker.io/myusername/myapp:latest
docker push localhost:5000/myapp:v1.0.0

Before pushing, you must tag the image with the registry URL. The registry URL prefix determines where Docker pushes the image. Docker Hub is the default if no registry is specified.

Complete workflow for building and pushing an image:

docker build -t myapp:1.0.0 .
docker tag myapp:1.0.0 myregistry.azurecr.io/myapp:1.0.0
docker push myregistry.azurecr.io/myapp:1.0.0

Login to Registries

The docker login command authenticates with registries:

docker login
docker login myregistry.azurecr.io
docker login -u username -p password registry.example.com
docker logout

The first command prompts for Docker Hub credentials. The second command logs into a specific registry. The third command provides credentials directly (use with caution in scripts). The docker logout command removes stored credentials.

Searching for Images

The docker search command finds images in registries:

docker search nginx
docker search --limit 25 postgres
docker search --filter "is-official=true" ubuntu

The first command searches for images containing "nginx" in Docker Hub. The --limit flag controls the number of results. The --filter option refines searches, such as showing only official images.

Docker Networking Commands

Creating and Managing Networks

The docker network commands enable container communication:

docker network create app-network
docker network create --driver bridge custom-bridge
docker network create --subnet=172.20.0.0/16 backend-network
docker network ls
docker network inspect app-network
docker network rm app-network

The first command creates a basic bridge network. The second command explicitly specifies the network driver. The third command creates a network with a custom subnet range. The docker network ls command lists all networks. The docker network inspect command shows detailed information about a network. The docker network rm command deletes a network.

Connecting Containers to Networks

These commands manage container network connections:

docker run -d --network app-network --name db postgres:15
docker run -d --network app-network --name web nginx:latest
docker network connect app-network existing-container
docker network disconnect app-network existing-container

The first two commands start containers already connected to a network. The third command adds an existing container to a network. The fourth command removes a container from a network.

Containers on the same network can communicate using container names as hostnames, enabling service discovery without external tools.

Docker Volume Commands

Creating and Managing Volumes

Volumes persist data beyond container lifetimes:

docker volume create app-data
docker volume ls
docker volume inspect app-data
docker volume rm app-data
docker volume prune

The first command creates a named volume. The docker volume ls command lists all volumes. The docker volume inspect command shows volume details including mount point. The docker volume rm command removes a volume. The docker volume prune command removes all unused volumes.

Using Volumes in Containers

Mount volumes when running containers:

docker run -d -v app-data:/app/data myapp:latest
docker run -d -v /host/path:/container/path myapp:latest
docker run -d -v app-data:/data --read-only myapp:latest
docker run -d --mount type=volume,src=myvolume,dst=/data myapp:latest

The first command mounts a named volume. The second command binds a host directory. The third command mounts a volume as read-only. The fourth command uses the --mount syntax, which is more explicit and recommended for complex configurations.

Backing up a volume demonstrates practical usage:

docker run --rm -v app-data:/data -v $(pwd):/backup ubuntu tar czf /backup/backup.tar.gz -C /data .

This command creates a temporary container, mounts the volume to back up and a host directory for output, compresses the data, and automatically removes the container after completion.

Docker System and Cleanup Commands

Checking System Information

These commands provide system-level information:

docker system df
docker system events
docker info
docker version

The docker system df command shows disk usage by images, containers, and volumes. The docker system events command streams real-time Docker events. The docker info command displays detailed system information. The docker version command shows Docker and API versions.

Comprehensive Cleanup Operations

Regular cleanup keeps your system healthy and free of wasted resources:

docker system prune
docker system prune -a
docker system prune -a --volumes
docker system prune --filter "until=720h"

The first command removes all stopped containers, dangling images, and unused networks. The -a flag also removes all unused images. The --volumes flag additionally removes unused volumes. The --filter option provides time-based filtering.

Create a cleanup script for scheduled maintenance:

#!/bin/bash
echo "Removing stopped containers..."
docker container prune -f

echo "Removing dangling images..."
docker image prune -f

echo "Removing unused volumes..."
docker volume prune -f

echo "Removing unused networks..."
docker network prune -f

echo "System cleanup complete."
docker system df

Advanced Container Inspection Commands

Detailed Container Inspection

The docker inspect command for containers provides comprehensive metadata:

docker inspect container_name
docker inspect --format='{{.State.Running}}' container_name
docker inspect --format='{{range .Mounts}}{{.Source}}{{end}}' container_name
docker inspect --format='{{json .NetworkSettings.Networks}}' container_name | jq .

The first command displays all container information in JSON format. The second command checks if a container is running. The third command lists all mounted volumes. The fourth command retrieves network configuration.

Copying Files Between Host and Container

The docker cp command transfers files:

docker cp container_name:/app/config.json ./config.json
docker cp ./local-file.txt container_name:/app/local-file.txt
docker cp container_name:/var/log/app.log logs/
docker cp container_id:path/to/file local/path/

These commands enable moving configuration files, logs, and other data between your host system and running containers.

Monitoring Container Performance

Track performance metrics over time:

docker stats --no-stream container_name
watch -n 1 'docker stats --no-stream'
docker events --filter type=container

The first command shows current stats. The second command refreshes stats every second. The third command streams container events as they occur.

Docker Compose Commands

Managing Multi-Container Applications

Docker Compose simplifies managing multiple related containers:

docker-compose up
docker-compose up -d
docker-compose up --build
docker-compose down
docker-compose ps
docker-compose logs
docker-compose exec service-name command

The first command starts all services defined in docker-compose.yml. The -d flag runs services in detached mode. The --build flag rebuilds images before starting. The down command stops and removes all services. The ps command lists running services. The logs command shows aggregated logs. The exec command runs commands in specific services.

Example docker-compose.yml file for a typical web application:

version: '3.8'
services:
  web:
    build: .
    ports:
      - "8080:3000"
    environment:
      - DATABASE_URL=postgresql://db:5432/myapp
    depends_on:
      - db
    networks:
      - app-network

  db:
    image: postgres:15
    environment:
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=myapp
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - app-network

  redis:
    image: redis:7-alpine
    networks:
      - app-network

volumes:
  db-data:

networks:
  app-network:

Start this stack with:

docker-compose up -d

Practical Command Examples and Workflows

Complete Development Workflow

Here is a realistic workflow from development through deployment:

docker build -t myapp:dev .
docker run -it -v $(pwd):/app -p 8080:3000 myapp:dev

For production, build a release version:

docker build -f Dockerfile.prod -t myapp:1.0.0 .
docker tag myapp:1.0.0 myregistry.azurecr.io/myapp:1.0.0
docker push myregistry.azurecr.io/myapp:1.0.0

Health Checking and Monitoring

Implement health checks in your containers:

docker run -d \
  --health-cmd="curl -f http://localhost:3000/health || exit 1" \
  --health-interval=30s \
  --health-timeout=10s \
  --health-retries=3 \
  --health-start-period=40s \
  myapp:latest

Check health status:

docker inspect --format='{{.State.Health.Status}}' container_name

Batch Operations Script

Perform operations on multiple containers:

#!/bin/bash
CONTAINERS=$(docker ps -q)
for container in $CONTAINERS; do
  echo "Processing $container"
  docker exec $container /app/maintenance.sh
done

Best Practices for Using Docker Commands

Always use specific version tags rather than latest in production. Never run containers as root unless absolutely necessary. Implement proper resource limits to prevent one container from consuming all system resources. Use health checks to ensure containers stay healthy. Organize containers into networks for improved security and service discovery. Mount volumes for data that must persist beyond container lifetime. Regularly clean up unused resources to maintain system efficiency. Use environment variables for configuration to keep containers portable. Implement proper logging strategies and centralize logs from all containers. Implement security scanning of images before deploying to production.

Conclusion

Mastering Docker commands is essential for any DevOps engineer working with containerized applications. This comprehensive guide has covered every major category of Docker commands, from basic image and container management to advanced networking, volume management, and monitoring. The practical examples provided demonstrate real-world scenarios you will encounter in production environments. Whether you are building development environments, deploying to production, or troubleshooting issues, these commands form the foundation of effective Docker usage. This article is part of the Docker Complete Course on learnwithirfan.com, where you can find additional resources, advanced topics, and hands-on tutorials to deepen your containerization expertise. Practice these commands regularly, automate common workflows, and you will develop the expertise needed to manage sophisticated container infrastructure efficiently and reliably.

Final Thoughts

Essential Docker Commands Every Engineer Should Know is worth reviewing with a practical lens: understand the risk or opportunity, map it to your environment, and take clear next steps instead of reacting to headlines.

FAQ: Essential Docker Commands Every Engineer Should Know

What should you know about Basic Docker Command Syntax?+

Every Docker command follows a predictable pattern that makes learning and remembering them straightforward. The basic syntax is: The OPTIONS modify how Docker executes the command, COMMAND specifies what action to perform, and ARG provides additional parameters for that command.

What should you know about Getting Help and Version Information?+

Before diving into specific commands, you should know how to access Docker documentation directly from your terminal.

What should you know about Pulling Images from Docker Registry?+

Before you can run a container, you need to have an image available on your system. The docker pull command downloads images from Docker registries, most commonly Docker Hub: The image name follows the format registry/repository:tag . If you omit the registry, Docker assumes Docker Hub.

What should you know about Listing Available Images?+

The docker images command displays all images stored on your system, along with useful metadata: The first command lists all images with default formatting showing repository, tag, image ID, creation time, and size.

What should you know about Building Custom Images?+

The docker build command creates custom images from a Dockerfile. This is one of the most important commands in your Docker workflow: The -t flag tags the image with a repository and version. The -f flag specifies an alternative Dockerfile when you have multiple build configurations.

Need help with infrastructure or security?

Work directly with Muhammad Irfan Aslam for Linux, cybersecurity, cloud, Docker, DevOps, CI/CD, or infrastructure support.

Hire Me for Support