Lesson 1.5: Running Containers
Welcome to Lesson 1.5! Now that you know how to manage images, it's time to bring them to life. In this lesson, you'll learn how to run containers, control their lifecycle, and inspect their behavior. By the end, you'll be comfortable launching, managing, and troubleshooting containers.
Learning Objectives
TIP
By the end of this lesson, you will be able to:
- Run containers in interactive and detached modes using
docker run. - Name containers and understand auto-generated names.
- Start, stop, restart, and remove containers.
- List running and stopped containers with
docker ps. - View logs and inspect container details.
- Execute commands inside running containers with
docker exec. - Manage container lifecycle effectively.
1. The docker run Command
The docker run command is the most fundamental command—it creates and starts a container from an image.
Basic syntax:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]IMAGEis the image name (e.g.,ubuntu,nginx).COMMANDoverrides the default command specified in the image.ARG...are arguments to that command.
Common Options
| Option | Description |
|---|---|
-d, --detach | Run container in background (detached mode). |
-it | Combine -i (interactive) and -t (pseudo-TTY) for interactive shell. |
--name | Assign a name to the container. |
-p, --publish | Publish container port(s) to the host. |
-v, --volume | Mount a volume. |
-e, --env | Set environment variables. |
--rm | Automatically remove container when it exits. |
--restart | Restart policy (e.g., always, on-failure). |
We'll explore many of these in later lessons; for now, focus on -d, -it, --name, and --rm.
2. Interactive vs. Detached Mode
2.1. Interactive Mode (-it)
Interactive mode keeps the container alive and lets you interact with it via your terminal. It's perfect for exploring a container or running a shell.
Example: Run an Ubuntu container and get a bash shell:
docker run -it ubuntu bashYou'll be dropped into the container's shell. Type exit or press Ctrl+D to leave—the container stops.
What happens?
-ikeeps STDIN open.-tallocates a pseudo-TTY (terminal).- Together they give you an interactive terminal session.
2.2. Detached Mode (-d)
Detached mode runs the container in the background. The container starts, and you get back your terminal prompt immediately.
Example: Run an Nginx web server in the background:
docker run -d nginxDocker prints the container ID and returns. Nginx keeps running.
You can verify it's running with docker ps.
3. Naming Containers
By default, Docker assigns a random name (like cool_hermann) to each container. While fun, these are hard to manage. Use --name to give your container a meaningful name.
Example:
docker run -d --name mynginx nginxNow you can refer to this container as mynginx in all subsequent commands.
WARNING
Container names must be unique. If you try to create another container with the same name, Docker will error.
4. Container Lifecycle
A container can be in various states: created, running, paused, stopped, deleted. Here are the key commands to manage its lifecycle.
4.1. docker create
Creates a container from an image but does not start it. Useful for preparing a container to start later.
docker create --name myubuntu ubuntu4.2. docker start
Starts one or more stopped containers.
docker start myubuntu4.3. docker stop
Stops a running container gracefully (sends SIGTERM, then SIGKILL after grace period).
docker stop mynginx4.4. docker restart
Stops and then starts a container.
docker restart mynginx4.5. docker pause / docker unpause
Pauses all processes in a container (freezes it) using cgroups freezer. Useful for debugging or taking snapshots.
docker pause mynginx
docker unpause mynginx4.6. docker kill
Forcefully stops a container immediately (sends SIGKILL).
docker kill mynginx4.7. docker rm
Removes one or more stopped containers. To remove a running container, use -f.
docker rm myubuntu
docker rm -f mynginx # force remove even if running4.8. --rm flag
If you add --rm to docker run, the container is automatically removed when it stops. Useful for temporary containers.
docker run --rm -it ubuntu bash
# after exit, container is gone5. Listing Containers
5.1. docker ps
Lists only running containers.
docker psOutput includes container ID, image, command, created, status, ports, and name.
5.2. docker ps -a
Lists all containers (running and stopped).
docker ps -a5.3. Filtering
You can filter the list, e.g., show only containers with a certain status:
docker ps -a --filter "status=exited"Or by name:
docker ps --filter "name=mynginx"5.4. Showing only container IDs
Useful for scripting:
docker ps -q6. Inspecting Containers
6.1. docker logs
View logs (stdout/stderr) from a container.
docker logs mynginx- Follow logs in real-time:
docker logs -f mynginx - Show timestamps:
docker logs -t mynginx - Tail last n lines:
docker logs --tail 10 mynginx
6.2. docker inspect
Returns detailed metadata about a container (or image) in JSON format.
docker inspect mynginxYou can filter specific fields with --format (Go templates). For example, get the container's IP address:
docker inspect --format='{{.NetworkSettings.IPAddress}}' mynginx6.3. docker stats
Display live resource usage statistics (CPU, memory, network I/O) for running containers.
docker statsPress Ctrl+C to exit.
6.4. docker top
Show running processes in a container.
docker top mynginx6.5. docker port
List port mappings for a container.
docker port mynginx7. Executing Commands in Running Containers
Sometimes you need to run a command inside an already running container—for debugging, configuration, etc. Use docker exec.
Syntax:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]Example: Open a bash shell inside a running Nginx container:
docker exec -it mynginx sh(If bash isn't available, try sh.)
Example: Run a single command without entering an interactive shell:
docker exec mynginx ls -l /etc/nginxOptions:
-i,-tsame asdocker run(usually used together for interactive).-drun command in background.-eset environment variables.--workdirset working directory.
Hands-On Tasks
Now it's time to practice. Complete these tasks to solidify your understanding.
[ ] Task 1: Run Interactive Containers
- Run an interactive Ubuntu container with bash:bash
docker run -it ubuntu bash - Inside the container, create a file:bash
echo "Hello from inside" > /tmp/test.txt - Exit the container (
exit). - Verify the container is stopped:
docker ps -a. Note its name.
- Run an interactive Ubuntu container with bash:
[ ] Task 2: Run Detached Containers
- Run an Nginx container in detached mode, naming it
web1:bashdocker run -d --name web1 nginx - Check that it's running:
docker ps. - View its logs:
docker logs web1.
- Run an Nginx container in detached mode, naming it
[ ] Task 3: Container Lifecycle
- Stop the
web1container:docker stop web1. - Confirm it's stopped:
docker ps -a. - Start it again:
docker start web1. - Restart it:
docker restart web1. - Pause it:
docker pause web1. Observe its status indocker ps. - Unpause:
docker unpause web1. - Kill it forcefully:
docker kill web1. - Remove it:
docker rm web1.
- Stop the
[ ] Task 4: Naming and Auto-removal
- Run a temporary container with
--rmand--name:bashdocker run --rm --name temp alpine echo "I'm temporary" - Immediately after, check
docker ps -a– the container should be gone.
- Run a temporary container with
[ ] Task 5: Inspect Containers
- Run a new Nginx container named
web2(detached). - Inspect it:
docker inspect web2. Look at theNetworkSettingssection. - Use
--formatto extract its IP address. - Check its resource usage:
docker stats web2(exit with Ctrl+C). - View its logs with timestamps:
docker logs -t web2.
- Run a new Nginx container named
[ ] Task 6: Execute Commands
- With
web2running, run a command to list files in the container:bashdocker exec web2 ls -l /usr/share/nginx/html - Open an interactive shell inside the container:bash(If bash not found, try
docker exec -it web2 bashsh.) - Inside, modify the default Nginx page (optional):bash
echo "<h1>Hacked!</h1>" > /usr/share/nginx/html/index.html exit - Verify the change by checking logs or using a web browser if you mapped ports (we'll cover ports in networking).
- With
[ ] Task 7: Clean Up Remove all containers you created:
docker stop $(docker ps -q) # stop all running
docker rm $(docker ps -aq) # remove all containers (force with -f if needed)WARNING
This removes all containers. Be sure you don't need them.
Summary
Key Takeaways
- Use
docker runto create and start containers, with-itfor interactive sessions and-dfor background. - Name containers with
--namefor easier management. - Lifecycle commands:
create,start,stop,restart,pause,unpause,kill,rm. - List containers with
docker psanddocker ps -a. - Inspect containers with
docker logs,docker inspect,docker stats,docker top. - Execute commands inside running containers with
docker exec.
Check Your Understanding
- What is the difference between
docker run -it ubuntu bashanddocker run -d ubuntu bash? - How do you list only stopped containers?
- What command would you use to see the last 20 lines of logs from a container named
myapp? - How can you get the IP address of a running container?
- If you want to run a temporary container that deletes itself after exiting, which flag do you use?
- How do you open a shell inside a running container named
database?
Click to see answers
-itruns interactively (attaches your terminal to the container);-druns detached (in the background).docker ps -a --filter "status=exited"docker logs --tail 20 myappdocker inspect --format='{{.NetworkSettings.IPAddress}}' mycontainer--rmdocker exec -it database bash(orshif bash isn't available)
Additional Resources
- Docker run reference
- Docker ps reference
- Docker logs reference
- Docker exec reference
- Docker inspect reference
- Container lifecycle management
Next Up
This concludes Phase 1: Docker Fundamentals. You now have a solid foundation: you understand containerization, installed Docker, know the architecture, can work with images, and run/manage containers. In the next phase, we'll start building custom images with Dockerfiles. Great job!