DevOps Peach

Docker & Kubernetes · Getting Started with Docker · Lesson 4 of 4

Basic Docker commands

The container lifecycle — run, ps, logs, exec, stop, rm — and the flags you use most.

Practice interactively →

Container lifecycle

stateDiagram-v2
  [*] --> Running: docker run
  Running --> Stopped: docker stop
  Stopped --> Running: docker start
  Stopped --> [*]: docker rm

The command you use most is docker run; it pulls the image (if missing), creates and starts the container:

docker run -d --name web -p 8080:80 nginx:1.27
Command Meaning
docker ps / docker ps -a Running containers / all, including stopped
docker logs web Show the container's stdout/stderr
docker exec -it web sh Open a shell in a running container
docker stop web / docker start web Stop / start the container again
docker rm web Remove a stopped container (-f also removes a running one)
docker rmi nginx:1.27 Remove an image (= docker image rm)

Management commands are the newer, equivalent spelling: docker container ls = docker ps, docker image ls = docker images, docker container run = docker run.

Common traps

More docker run flags you will use

Flag Meaning
-e KEY=value, --env-file .env Set environment variables
-v data:/var/lib/app Mount a volume
--rm Remove the container when it exits
-it Interactive terminal, for shells
--restart unless-stopped Restart after crashes and daemon restarts
--memory 512m --cpus 1 Limit memory and CPU
-u 1000:1000 Run as a specific user

Looking inside

Exit codes tell a story

Code Usual meaning
0 The main process finished normally
1 Application error
125 docker run itself failed (bad flag, name conflict)
127 Command not found inside the image
137 Killed by SIGKILL, often the out-of-memory killer or docker kill
143 Stopped by SIGTERM, a normal docker stop

docker ps -a shows the exit code in the STATUS column, and docker inspect -f '{{.State.OOMKilled}}' web confirms a memory kill.

Cleaning up

Stopped containers, unused images, and build cache pile up quickly. docker system df shows how much space each uses. docker container prune, docker image prune -a, and docker builder prune remove them selectively; docker system prune removes stopped containers, unused networks, dangling images, and build cache in one go (add --volumes only when you are sure no data is needed).

Practice interactively →