Practical Examples and Use Cases
Now that you have a basic understanding of Docker containers and how to interact with processes running inside them, let's explore some practical examples and use cases.
Running a Web Server in a Docker Container
One common use case for Docker is running web applications. Let's run a simple Nginx web server in a Docker container.
## Pull the Nginx image from Docker Hub
docker pull nginx:latest
## Run an Nginx container
docker run -d -p 80:80 --name my-nginx nginx:latest
## Access the web server in your browser
http://localhost
In this example, we pulled the Nginx image from Docker Hub, ran a container based on that image, and mapped port 80 on the host to port 80 in the container. You can now access the Nginx web server running in the container by visiting http://localhost
in your web browser.
Scaling a Containerized Application
Docker makes it easy to scale your applications by running multiple instances of a container. You can use Docker Compose to define and manage multiple containers as a single application.
## docker-compose.yml
version: '3'
services:
web:
image: nginx:latest
ports:
- 80:80
deploy:
replicas: 3
In this example, we define a web
service that runs the Nginx web server. We specify that we want to run 3 replicas of the web service, and Docker Compose will automatically manage the scaling of the containers.
Debugging a Containerized Application
When issues arise with your containerized application, you can use the Docker commands you learned earlier to debug and troubleshoot the problem.
## List the running containers
docker ps
## Access the shell of a running container
docker exec -it <container_id> /bin/bash
## View the logs of a container
docker logs <container_id>
By using these commands, you can inspect the running processes, access the container's file system, and view the logs to help identify and resolve any issues with your containerized application.
These are just a few examples of how you can use Docker to run, scale, and debug your applications. The flexibility and portability of Docker containers make them a powerful tool for modern software development and deployment.