Lesson 08/10 minutes/2 graded
The main Docker commands
The dozen commands worth knowing, the difference between run and start, and how to get a shell inside a running container.
You have met most of these already, spread across the last few lessons. Here they are in one place, because this is the handful I actually type all day.
| Command | What it does |
|---|---|
docker pull | Downloads an image from a registry |
docker images | Lists the images on your machine |
docker run | Creates a new container from an image and starts it |
docker ps | Lists running containers |
docker ps -a | Lists every container, running or stopped |
docker logs | Prints what the app inside a container printed |
docker stop | Stops a running container |
docker start | Starts a container you stopped earlier |
docker exec | Runs a command inside a running container |
docker rm | Deletes a container |
docker rmi | Deletes an image |
docker build | Builds an image from a Dockerfile |
run creates, start reuses
This is the one to get straight, because getting it wrong leaves junk all over your machine.
docker run always makes a new container. Run the same image four times and
you have four containers, three of which you have probably forgotten about.
docker start takes a container that already exists, by name or id, and starts
it again with the settings it was created with. Your port bindings and your name
come back as they were, because it is the same container.
So when you want your app back after stopping it, start is the command. run
is for when you want a fresh one.
Watching logs as they happen
docker logs web prints everything the app has written so far and returns. Add
-f and it stays open, printing new lines as they arrive, which is what you
want while clicking around in the browser:
docker logs -f web
Ctrl+C ends the log stream. It does not stop the container.
Getting a shell inside the container
Sometimes you need to look around in there. Is my file where I copied it? Is this environment variable actually set?
docker exec -it web sh
You land in a shell inside the running container, in the folder your WORKDIR
set. -it is what makes it interactive, so you can type. When I did this in my
node app image, ls showed exactly what I copied plus the node_modules folder
that npm install created, and node -v printed v24.19.0.
Type exit to leave. The container keeps running.
Cleaning up
docker ps -a is where you see how much you have piled up. Delete a container
you are done with:
docker rm web
A running container will not be deleted, so stop it first. Images work the same
way with docker rmi, and an image being used by a container will not go until
that container does.