Mastering Docker Containers: Bringing Blueprints to Life
7 min read
In the previous chapters, we looked at Docker Images—the read-only templates or "blueprints" of our applications. But a blueprint alone cannot serve web traffic or calculate data. It needs to be built and executed.
A Docker Container is a runnable instance of an image. You can create, start, stop, move, or delete a container. While an image is simply files resting on your disk, a container is a live, breathing process executing those files within an isolated environment.
Let's explore how to manage these live instances effectively.
1. Container Lifecycle: Run, Start, Stop, and Remove 🔄
The Problem
Software applications are dynamic. You need a way to launch an application safely, pause it when taking backups, stop it when it is misbehaving, and completely destroy it to free up server resources when it is no longer needed. If you run software directly on your host machine, stopping and cleaning up all associated background processes and temporary files is notoriously difficult.
The Solution
Docker provides explicit, simple commands to control the lifecycle of a container. Because a container is isolated, stopping and removing it guarantees that 100% of its running processes and temporary internal states are wiped clean from your machine.
Here is the standard lifecycle flow:
- Create + Start = Run: The command you will use 99% of the time. It takes an image, creates a fresh container from it, and immediately starts it.
- Stop: Gracefully halts the container's processes.
- Start: Wakes up a previously stopped container.
- Remove (rm): Deletes the container completely.
Hands-on Practice
Let's run a simple Nginx web server container:
# This downloads the nginx image (if not already local) and runs it.
docker run nginxInteresting Fact: If you press Ctrl+C right now, your terminal sends a "kill" signal to the container, stopping it. But the container isn't gone; it is just resting on your hard drive.
To view all containers, including the stopped ones:
docker ps -aTo start a stopped container, you grab its ID from the previous command and run:
docker start <CONTAINER_ID>To cleanly stop a running container:
docker stop <CONTAINER_ID>Finally, a stopped container still consumes disk space. If you forget to delete them, Docker will hoard these inactive containers like a digital packrat, eventually filling up your hard drive. To delete it:
docker rm <CONTAINER_ID>Industry Standard: In CI/CD pipelines and local development, engineers frequently append the --rm flag. This tells Docker: "As soon as this container stops, automatically delete it."
docker run --rm nginxUnder the Hood
When you run a container, the Linux kernel uses namespaces to give the process its own isolated filesystem, network, and process tree. It uses cgroups to limit how much RAM and CPU it can use. When you docker stop, Docker sends a SIGTERM signal to the main process (PID 1) inside the container, giving it 10 seconds to save data and exit gracefully before forcefully killing it with SIGKILL.
2. Detached vs. Interactive Modes: How to Run Containers 🕹️
The Problem
When you type docker run nginx in your terminal, the container takes over your console. The web server's logs start printing on your screen, and you cannot type any other commands. You have entered a terminal hostage situation. Conversely, sometimes you want to interact with a container (like an Ubuntu image) to test some Linux commands, but Docker immediately exits because it thinks its job is done.
The Solution
Docker provides two distinct modes for running containers based on your workflow: Detached Mode (-d) and Interactive Mode (-it).
Imagine you are managing employees in a restaurant.
- Detached Mode is like hiring a dishwasher. You tell them to start working, and they go to the back room and handle it. You are free to do other things.
- Interactive Mode is like training a new cashier. You need to stand right next to them, watching what they do and speaking directly to them.
Hands-on Practice
1. Detached Mode (-d)
Used for background services like web servers, databases, and message queues.
docker run -d nginxResult: Docker prints a long ID (e.g., a1b2c3d4...) and instantly gives you your terminal prompt back. The Nginx server is happily running in the background.
2. Interactive Mode (-it)
This is actually two flags: -i (keep input open) and -t (allocate a pseudo-TTY/terminal). Used for debugging, running shell scripts, or exploring a system.
docker run -it ubuntu bashResult: Your terminal prompt changes. You are no longer on your host operating system; you are now completely inside the isolated Ubuntu container, typing commands directly into its shell. Typing exit will stop the container and return you to your host.
3. Port Mapping: Connecting Containers to the Outside World 🔌
The Problem
By design, containers are placed in solitary confinement. If you run an Nginx container, it successfully starts a web server on port 80 inside the container. However, if you open your host computer's web browser and go to http://localhost:80, you will get a "Site can't be reached" error. The host machine is completely unaware of the container's internal network.
The Solution
We must explicitly drill a hole through the container's isolation to connect an internal port to an external port on your host machine. This is called Port Mapping or Port Publishing.
Think of a large apartment building (your host machine) with a single public street address. Inside, there are hundreds of private apartments (containers). If a package arrives at the building, the mail carrier doesn't know which apartment it belongs to. You need a directory board (port mapping) that says, "All mail sent to Mailbox 8080 should be delivered to Apartment 1, Room 80."
Hands-on Practice
We use the -p (publish) flag followed by HOST_PORT:CONTAINER_PORT.
docker run -d -p 8080:80 nginxHere is what just happened:
- Nginx started running inside the container on its default port, 80.
- We told Docker to grab port 8080 on our actual computer (the host).
- Docker mapped our host's
8080to the container's80.
Now, if you open your web browser and navigate to http://localhost:8080, you will see the default "Welcome to nginx!" screen.
Industry Standard: Never map to well-known host ports (like 80 or 443) directly during local development, as your operating system might already be using them for system services. Always map to higher range ports like 8080, 3000, or 8000.
4. Naming, Inspecting, and Executing Commands 🕵️♂️
The Problem
When you run a container in detached mode, Docker generates an automatic name for it. It uses an adjective and a famous scientist's or hacker's name (e.g., quirky_einstein, suspicious_bohr). While hilarious, managing 15 containers with names like naughty_newton is an operational nightmare.
Furthermore, once a container is running in the background, how do you see its logs? Or what if the app crashes and you need to poke around inside the live container to read an error file?
The Solution
We use --name to assign predictable labels. We use docker logs and docker inspect to observe from the outside, and docker exec to break into a running container.
Hands-on Practice
1. Naming your containers
Always name your containers based on their role.
docker run -d --name frontend-web-app -p 8080:80 nginxFunny Fact: Docker's random name generator contains a specific rule to never generate boring_wozniak because Steve Wozniak is never boring.
2. Viewing Logs
Since the container is running in detached mode, its output isn't on our screen. To view the access logs of our web server:
docker logs frontend-web-app(Pro-tip: Add -f to "follow" the logs live, just like tail -f in Linux).
3. Inspecting
Need to know the specific internal IP address Docker assigned to this container, or what environment variables are set inside?
# Outputs a massive JSON object with every configuration detail imaginable
docker inspect frontend-web-app 4. Executing Commands (The Backdoor)docker exec allows you to run a new command inside an already running container. This is heavily used in the industry for troubleshooting.
Let's open a shell inside our running Nginx container to look at the config files:
docker exec -it frontend-web-app bashNotice we used -it again! Because we want an interactive terminal. Once inside, you can run ls /etc/nginx to debug your configuration, then type exit to leave. Unlike docker run, exiting an exec session does not stop the container. The web server keeps running perfectly.
References for Extra Reading 📚
Challenge
You are a DevOps engineer tasked with deploying and managing a simple application using Docker. Write the sequence of Docker commands necessary to perform the following operations in order.
Start a new NGINX web server container based on the
nginx:latestimage. The container must:- Run in the background (detached mode).
- Be named
my-web-server. - Map port
8080on the host to port80inside the container.
Deploy a Redis database container using the
redis:alpineimage. This container must:- Run in the background.
- Be named
cache-db. - Be automatically removed when it is stopped.
After the web server is running, execute a command inside the
my-web-servercontainer to list the contents of the/usr/share/nginx/htmldirectory. The command must be executed interactively.Retrieve all the logs generated by the
cache-dbcontainer since it started.Gracefully stop the
my-web-servercontainer.After stopping the web server, permanently delete it to free up system resources.
Expected result
Your solution should consist of six distinct Docker commands, each on a new line, corresponding to the six tasks in the instructions.
- A
docker runcommand for the NGINX container using the-d,--name, and-pflags with the specified values (my-web-server,8080:80). - A
docker runcommand for the Redis container using the-d,--name, and--rmflags. - A
docker execcommand targetingmy-web-server, using the-itflags to run thels /usr/share/nginx/htmlcommand. - A
docker logscommand targetingcache-db. - A
docker stopcommand targetingmy-web-server. - A
docker rmcommand targetingmy-web-server.
The final code should be structured as follows:
docker run -d --name my-web-server -p 8080:80 nginx:latest
docker run -d --name cache-db --rm redis:alpine
docker exec -it my-web-server ls /usr/share/nginx/html
docker logs cache-db
docker stop my-web-server
docker rm my-web-server