Lesson 2: Your First Container
Time to get your hands dirty. Let's run real containers and understand how they work from the inside.
Running a Container: docker run
The docker run command creates and starts a container from an image:
docker run ubuntu echo "Hello from inside a container!"
What just happened:
- Docker checked if the
ubuntuimage exists locally. - If not, it pulled it from Docker Hub (the public registry).
- It created a container from the image.
- It ran
echo "Hello from inside a container!"inside it. - The container stopped (its job was done).
Interactive Mode: -it
To get a shell inside a container (like SSH-ing into a server):
docker run -it ubuntu bash
-i— Interactive (keep stdin open).-t— TTY (allocate a terminal).
You're now inside the container! It's a fresh, isolated Ubuntu environment. Type exit to leave.
Common docker run Flags
| Flag | Purpose | Example |
|------|---------|---------|
| -it | Interactive terminal | docker run -it ubuntu bash |
| -d | Detached (background) | docker run -d nginx |
| --name | Give the container a name | docker run --name web nginx |
| --rm | Auto-remove when stopped | docker run --rm ubuntu echo hi |
| -p | Map a port | docker run -p 8080:80 nginx |
| -e | Set environment variable | docker run -e DB_HOST=localhost app |
Listing Containers
docker ps # Show RUNNING containers only
docker ps -a # Show ALL containers (including stopped)
docker ps -q # Show only container IDs
The Container vs. Image Mental Model
Think of it like baking:
- Image = The recipe 📜 (read-only blueprint)
- Container = The cake 🎂 (a running instance of the recipe)
You can bake many cakes from one recipe. Each cake is independent — decorating one doesn't change the others.
docker run -d --name web1 nginx # Cake 1
docker run -d --name web2 nginx # Cake 2
docker run -d --name web3 nginx # Cake 3
# All from the same recipe (nginx image)
Mission Objective
Launch and explore your first containers:
- Dive in: Run
docker run -it ubuntu bashto enter an Ubuntu container. - Check the fleet: Run
docker psto see running containers. - See everything: Run
docker ps -ato see all containers, including stopped ones.