Card 02/ 06
Running nginx and Opening It in a Browser
A web server you never installed, serving a page on your machine in three commands.
Running a web server from an image (the packaged program and its files) takes three commands: start the container (a running copy of the image) with a published port (one made reachable from your machine), check that it is up, and open the page. The example uses nginx, a widely used web server, and finishes by stopping and removing the container.
Before you start, Docker must be running, and nothing else on your machine should be using port 8080.
Running nginx and reaching it from the browser
Start the container
docker run -d --name web -p 8080:80 nginx
9f2c1b7e4a83-d runs the container in the background (detached) and prints its id. --name web gives it a name, so later commands can say web instead of that id. -p 8080:80 publishes a port: connections to port 8080 on your machine are forwarded to port 80 inside the container, where nginx listens. If the image is not on your machine yet, Docker downloads it first.
Check that it is running
docker ps --format '{{.Names}}\t{{.Status}}\t{{.Ports}}'
web Up 4 seconds 0.0.0.0:8080->80/tcp, [::]:8080->80/tcpdocker ps lists running containers, and the format string picks three columns. Up 4 seconds means the program is running, and the last column confirms that port 8080 on your machine forwards to port 80 in the container.
Open the page
curl -s localhost:8080 | head -4
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>curl fetches the page from the command line, and head -4 keeps its first four lines. Opening http://localhost:8080 in a browser shows the same page, served by a program that is not installed on your machine.
Stop and remove it
docker stop web && docker rm web
web
webThese are two commands because they do two things: docker stop ends the program, and docker rm discards the container and its writable layer, the private area holding every file it changed. Each prints the name of the container it acted on.
You know it worked when the page title reads "Welcome to nginx!", and after the last step docker ps -a no longer lists web. The same commands, with a different image and port, run almost any server someone has packaged as an image.
← → move through sections and cards