Skip to content

Latest commit

 

History

History

lesson-7

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Pull NGINX image

In this lesson, we'll be using NGINX to serve some data over HTTP.

For that we'll need our container to be accessible from outside.

Let's pull the image first.

$ docker pull nginx:latest

Mount a port

Now run its container.

$ docker run -it --publish 8080:80 nginx:latest

The nginx:latest image runs a service on port 80 which serves some files. But we want that service to be accessible from localhost:8080. So we have published or mounted the port 80 of the container to port 8080 of our host machine.

On a different terminal of your host machine, or on your browser, visit http://localhost:8080

$ curl http://localhost:8080

After you'll visit the page, you'll see some logs generated by nginx on your terminal.

Also notice that, you cannot close the terminal where you started the container. If you close it, the container will stop.

Running container in background

Let's close it with CTRL-C and run it in background this time.

$ docker run -it --detach -p 8080:80 nginx:latest

Now the container runs in the background and it can be stopped using docker stop command.

Mount a volume

The NGINX default page has some boring stuff. NGINX serve that page from /usr/share/nginx/html/index.html inside the container. We need to change that.

You have two options,

  • copy a new index.html to that directory using ADD or docker cp command
  • mount a directory on your host machine to that directory in the container

First option is boring, let's do the second one.

Let's setup first the page to serve on our machine.

$ mkdir ~/my-website && cd ~/my-website
$ echo "My name is <b>Ali Yousuf</b>" > index.html

Let's run the container with this directory mounted.

$ docker run -dit -p 8080:80 --volume ~/my-website:/usr/share/nginx/html/ nginx:latest

You must have guessed it by now. It is --volume <src path>:<dst path>.

Yay! You just served your first website using Docker! 🎉

The benefit of mounting a volume is, if you change the file on your host machine, it will be reflected inside the container immediately. Let's try it.

$ echo " and I'm learning how to use Docker" >> index.html
$ curl http://localhost:8080

That's pretty useful.

Let's see another way how containers can be useful with volume mounts in the next lesson.