Run a Web Server in a Container
A web server in a container serves pages from inside the container, through a port mapped to the host. The -d flag runs it in the background, and -p maps the port.
Start nginx in the background
This command starts nginx detached, with port 8080 mapped.
docker run -d --name g3-web -p 8081:80 nginx:1.27-alpine >/dev/nullAsk the server for its page
curl fetches the welcome page from the mapped port.
curl -s http://localhost:8081/ | head -5Example
docker run -d --name g3-web -p 8081:80 nginx:1.27-alpine >/dev/null
curl -s http://localhost:8081/ | head -5Key points
- nginx: a small, fast web server, shipped as a Docker image.
- -d runs the container detached, in the background.
- -p 8080:80 maps host port 8080 to container port 80.
- Open http://localhost:8080 in a browser to see the welcome page.
- Use docker stop to stop the server when done.
In this example, Docker starts nginx in the background and maps host port 8081 to container port 80. curl fetches the welcome page through the mapped port. The page proves the server runs inside the container and answers on the host.
Note
The container port is 80 inside. The host port is yours to choose.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does -p 8081:80 do?