Lesson 5: Managing Container Lifecycles
In real-world scenarios, we need containers to run continuously in the background. This requires managing their state: starting, stopping, pausing, and removing.
Running Containers in Detached Mode
To run a container in the background (detached mode), we use the -d flag. Let's run a lightweight Nginx web server:
bash docker run -d --name my_web_server -p 8080:80 nginx
Breakdown:
-d: Detached mode (runs in the background).--name my_web_server: Assigns a readable name instead of a random ID.-p 8080:80: Port Mapping. Maps port 80 inside the container to port 8080 on our host machine.nginx: The image to use.
Now, check the running container:
bash docker ps
You should see my_web_server listed, showing its status as Up and the port mapping 0.0.0.0:8080->80/tcp.
You can now access the Nginx welcome page by navigating to http://localhost:8080 in your web browser.
Stopping and Starting Containers
Containers can be managed using their assigned name or ID.
1. Stopping
bash docker stop my_web_server
Check docker ps again; the container should be gone from the running list, but it still exists (check docker ps -a).
2. Starting
bash docker start my_web_server
3. Restarting
bash docker restart my_web_server
Removing Containers
To permanently delete a stopped container, use docker rm.
bash docker rm my_web_server
Tip: To remove all stopped containers efficiently, you can use:
bash docker container prune