Your First Container: Run, Stop, and Remove Without Breaking Anything
Your first docker run, safely: ps, logs, exec, stop and rm, port publishing, environment variables, restart policies and clean-up.
run, ps, logs, exec, stop, start, restart, rm, inspect and prune. Learn them with throwaway containers first, publish ports on 127.0.0.1 unless you mean to expose a service, give containers names, and remember the two rules that prevent most accidents: removing a container deletes its writable data, and docker system prune --volumes deletes your databases.
The first week with Docker usually leaves a laptop with forty stopped containers named things like quirky_hopper, a database whose data disappeared after a restart, and a development Postgres accidentally reachable from the coffee shop Wi-Fi. None of that is Docker misbehaving. It is the defaults doing exactly what they say, and a few habits avoid all of it.
This walkthrough uses two real images, nginx and postgres, so you can follow along. If you want the background on what an image and a container actually are, start with images, containers and layers.
Run a web server
docker run -d --name web -p 127.0.0.1:8080:80 nginx:1.23
| Part | Meaning |
|---|---|
-d |
Detached: run in the background and print the container ID |
--name web |
A name you can use instead of the ID in every other command |
-p 127.0.0.1:8080:80 |
Publish container port 80 on port 8080 of the host’s loopback interface only |
nginx:1.23 |
The image and an explicit tag, rather than an implicit latest |
Open http://localhost:8080 and you see the nginx welcome page. Docker pulled the image if it was not already present, created a container with its own writable layer and network namespace, and started nginx as its main process.
Why 127.0.0.1 matters
-p 8080:80 without an address binds to all interfaces, so the port is reachable from any network the machine is on. On a Linux server it is worse: Docker writes its own iptables rules for published ports, which are evaluated before the rules that firewalls like ufw manage. A port you believe is blocked by ufw can be wide open. Bind development services to 127.0.0.1, and on servers put services behind a reverse proxy or configure the DOCKER-USER iptables chain deliberately.
See what is running
docker ps # running containers
docker ps -a # all containers, including stopped ones
docker logs web # everything the container wrote to stdout and stderr
docker logs -f --tail 50 web # follow new output, starting from the last 50 lines
docker inspect web # full configuration and state as JSON
docker stats --no-stream # CPU and memory per container
Containerized applications should log to standard output and standard error, not to files. Docker captures those streams, and docker logs shows them. Official images such as nginx already redirect their log files to stdout for exactly this reason.
Get a shell inside
docker exec -it web sh # start an interactive shell in the running container
docker exec web nginx -t # run a single command and exit
exec starts an additional process inside the existing container’s namespaces. It is the right tool for looking around: checking a config file, testing DNS, reading environment variables. It is the wrong tool for changing things. Anything you install or edit there lives only in that container’s writable layer and disappears when the container is recreated. Put fixes in the Dockerfile.
Many minimal images do not include bash; sh is the safer default, and some images have no shell at all.
Run a database with configuration
docker run -d --name db \
-e POSTGRES_PASSWORD=devpassword \
-e POSTGRES_DB=app \
-v pgdata:/var/lib/postgresql/data \
-p 127.0.0.1:5432:5432 \
postgres:15
-e sets environment variables, which is how most images are configured. -v pgdata:/var/lib/postgresql/data stores the database files in a named volume called pgdata, outside the container’s writable layer. Without that line, the data lives in the container and is deleted along with it. Volumes have their own guide; for now, the rule is simple: any container that stores data you care about needs a volume.
The container lifecycle
created --start--> running --stop--> exited --start--> running
| |
pause rm
v v
paused (gone, writable layer deleted)
docker stop web # send SIGTERM, wait up to 10 seconds, then SIGKILL
docker start web # start the same container again, with its writable layer intact
docker restart web # stop then start
docker kill web # send SIGKILL immediately
docker rm web # delete a stopped container
docker rm -f web # stop and delete in one step
docker stop asks nicely first. The main process receives SIGTERM and has ten seconds (change it with -t) to shut down cleanly before Docker sends SIGKILL. If every docker stop on your own image takes exactly ten seconds, the process is not receiving or handling the signal. The usual cause is a Dockerfile CMD written in shell form, where a shell runs as PID 1 and does not forward signals to your application. The Dockerfile article covers the fix; running with --init is a quick workaround that adds a tiny init process to forward signals.
Throwaway and interactive containers
docker run --rm -it python:3.11 python # a Python REPL, deleted on exit
docker run --rm -v "$PWD":/work -w /work node:18 npm test # run tests in a clean Node 18
--rm removes the container automatically when it exits, which is ideal for one-off commands and the habit that prevents a graveyard of stopped containers. -it gives you an interactive terminal.
Restart policies
| Policy | Behavior |
|---|---|
no (default) |
Never restart automatically |
on-failure[:5] |
Restart if it exits with a non-zero code, optionally at most 5 times |
unless-stopped |
Always restart, including after a reboot, unless you stopped it manually |
always |
Always restart, even if you had stopped it, once the daemon restarts |
For a small service on a single server, --restart unless-stopped keeps it running across crashes and reboots. For anything with several services, Docker Compose manages this better.
Cleaning up without losing data
docker container prune # remove all stopped containers
docker image prune # remove dangling images (untagged build leftovers)
docker image prune -a # remove every image not used by a container
docker system df # see what is using disk space
docker system prune # stopped containers, unused networks, dangling images, build cache
None of these remove volumes by default, and that is deliberate. docker system prune --volumes and docker volume prune do remove unused volumes, which includes the volume of a database whose container you just removed. Read the confirmation prompt every time.
Frequently Asked Questions
What is the difference between docker stop and docker rm?
docker stop shuts down the container’s process but keeps the container and its writable layer, so docker start can bring it back. docker rm deletes the container and its writable layer permanently. Data in volumes is not affected by either.
Why does docker stop take 10 seconds?
Docker sends SIGTERM and waits up to 10 seconds before sending SIGKILL. If your process does not handle SIGTERM, or a shell running as PID 1 does not forward it, Docker waits the full timeout. Use the exec form of CMD or run with –init so the signal reaches your application.
Why did my container’s data disappear?
Data written inside a container lives in its writable layer, which is deleted when the container is removed or recreated. Store data that must persist in a named volume or bind mount.
Is it safe to run docker system prune?
Without flags, it removes stopped containers, unused networks, dangling images and build cache, but not volumes. Adding –volumes also deletes unused volumes, which can include database data, so use that flag only when you are sure.
Good habits from day one
Name your containers, pin image tags, bind development ports to localhost, use --rm for one-off commands, give every stateful container a volume, and look before you prune. With those habits, experimenting with Docker is safe: any container can be deleted and recreated in seconds, which is exactly what makes it useful. For the full reference, see the docker container run reference and the Docker getting started guide. Related reading on this site: how containers differ from virtual machines.
Originally posted on 23 February 2023 and post last modified on 23 February 2023