Docker Commands

A practical reference to the Docker CLI commands you use daily: run, exec, logs, build, ps, inspect, and cleanup, with examples.

Most day-to-day Docker work comes down to a small set of commands for running containers, inspecting them, building images, and cleaning up. This lesson groups them by task so you can recall them quickly during work and interviews. Current Docker supports both the short form (docker ps) and the grouped form (docker container ls); they do the same thing.

Running Containers

# Run in the foreground
docker run nginx:1.27

# Run detached with a name and a published port
docker run -d --name web -p 8080:80 nginx:1.27

# Interactive shell, removed on exit
docker run -it --rm alpine sh

# Environment variables, restart policy, resource limits
docker run -d --name db \
  -e POSTGRES_PASSWORD=secret \
  --restart unless-stopped \
  --memory 512m --cpus 1 \
  postgres:16
Flag Meaning
-d Detached (background)
-it Interactive with a pseudo-terminal
--rm Remove the container when it exits
--name Assign a name
-p host:container Publish a port
-e KEY=value Set an environment variable
-v source:target Mount a volume or bind mount
--network Attach to a specific network
--restart Restart policy (no, on-failure, always, unless-stopped)
--memory, --cpus Resource limits

Listing and Inspecting

docker ps                  # running containers
docker ps -a               # all containers, including stopped
docker ps -q               # only IDs
docker images              # local images (same as docker image ls)

docker inspect web                                   # full JSON
docker inspect --format '{{.State.Status}}' web      # running
docker inspect --format '{{.NetworkSettings.IPAddress}}' web

docker top web             # processes inside the container
docker stats               # live CPU, memory, network, I/O
docker diff web            # files changed in the writable layer

Logs and Debugging

docker logs web                 # all logs
docker logs -f --tail 100 web   # follow the last 100 lines
docker logs --since 10m web     # last 10 minutes

docker exec -it web sh          # shell in a running container
docker exec web nginx -t        # run a single command

docker cp web:/etc/nginx/nginx.conf ./nginx.conf   # copy out
docker cp ./index.html web:/usr/share/nginx/html/  # copy in

docker exec runs an additional process in an existing container. docker attach connects to the main process, which is rarely what you want.

Lifecycle Control

docker stop web      # SIGTERM, then SIGKILL after 10 seconds by default
docker stop -t 30 web  # wait 30 seconds before SIGKILL
docker kill web      # SIGKILL immediately
docker start web
docker restart web
docker pause web && docker unpause web
docker rm web        # remove a stopped container
docker rm -f web     # force-remove a running container

Images

docker pull postgres:16
docker build -t my-app:1.0 .
docker build -t my-app:1.0 -f docker/Dockerfile .
docker tag my-app:1.0 myuser/my-app:1.0
docker push myuser/my-app:1.0
docker history my-app:1.0
docker rmi my-app:1.0
docker save -o my-app.tar my-app:1.0    # export to a tar file
docker load -i my-app.tar               # import from a tar file

Volumes and Networks

docker volume create pgdata
docker volume ls
docker volume inspect pgdata
docker network create appnet
docker network ls
docker network inspect appnet

Cleanup

docker container prune       # remove all stopped containers
docker image prune           # remove dangling images
docker image prune -a        # remove all images not used by a container
docker volume prune          # remove unused local volumes (data loss risk!)
docker system df             # show disk usage
docker system prune          # stopped containers, unused networks, dangling images, build cache

docker system prune does not remove volumes unless you add --volumes, and that flag permanently deletes data.

Useful Combinations

# Stop and remove all running containers
docker rm -f $(docker ps -aq)

# Remove only exited containers
docker rm $(docker ps -aq --filter status=exited)

# Show container name and status as a table
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'

Common Mistakes

  • Forgetting --rm for throwaway containers. Stopped containers pile up.
  • Running docker volume prune or system prune --volumes carelessly. It can delete database data.
  • Using docker attach instead of docker exec. Pressing Ctrl+C may stop the main process.
  • Publishing ports without thinking about binding. -p 5432:5432 exposes the port on all host interfaces; use -p 127.0.0.1:5432:5432 for local-only access.
  • Not naming containers. Random names make scripts and troubleshooting harder.

Best Practices

  • Use --name and --rm deliberately, and pin image tags.
  • Prefer docker exec for debugging and docker logs -f for tailing output.
  • Use --format with docker inspect and docker ps to extract just what you need.
  • Review docker system df before pruning, and avoid pruning volumes on shared hosts.

Interview Questions

1. What is the difference between docker run, docker start, and docker exec?

docker run creates a new container from an image and starts it. docker start restarts an existing stopped container. docker exec runs an additional command inside an already running container.

2. What is the difference between docker stop and docker kill?

docker stop sends SIGTERM so the application can shut down gracefully, then SIGKILL after a timeout (10 seconds by default). docker kill sends SIGKILL (or another signal with -s) immediately.

3. How do you see why a container is failing?

Run docker ps -a for the status and exit code, then docker logs <container>. Use docker inspect for details such as State.ExitCode and State.OOMKilled.

4. What is the difference between docker rm and docker rmi?

docker rm removes containers; docker rmi removes images. An image cannot be removed while a container (even a stopped one) is using it unless forced.

5. How do you get a shell inside a running container?

docker exec -it <container> sh (or bash if available). For a stopped or crashing container, start a new one with docker run -it --entrypoint sh <image>.

6. How do you clean up unused Docker resources?

Use docker system df to review usage, then docker container prune, docker image prune -a, or docker system prune. Volumes are only pruned with docker volume prune or docker system prune --volumes.

Summary

  • run, ps, logs, exec, stop, and rm cover most daily work.
  • docker build, tag, and push handle images; inspect --format extracts exact fields.
  • docker stop is graceful, docker kill is immediate.
  • Prune carefully, especially volumes.

Continue Learning

Previous: Docker Image vs Container | Next: Docker Volumes

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.