Skip to content

Docker and Port Forwarding

Sometimes just running a simple command isn't enough. Sometimes we need to run a service inside a container, like a webserver, and then access the webserver on its port.

Even better would be, to say "Hey, map port 80 inside the container to port 8080 outside of the container". And that's exactly what you can do with Port forwarding!

Video Walkthrough

View the Full Course Now

Text Walkthrough

In this example we are starting an apache webserver hosting a single file

docker run --rm -d --name apacheserver httpd
  • Will start an apache in detached mode (-d)
  • It should open a webserver on port 80
  • It will give the container a name "apacheserver"
  • It will remove the container when it stops

Open http://localhost:80

  • That doesn't do anything
  • But is the Web-Server really running?
  • How can we test this, even though we can't access it?! 🤔
docker exec -it apacheserver /bin/bash
  • You get an interactive shell inside the container
apt-get update && apt-get install curl

and then

curl localhost:80
  • Should bring up a "it works" message, which means the webserver is running (the exact output is: <html><body><h1>It works!</h1></body></html>)
  • But why can't we see it on the host?

Let's exit the container and try something else...

exit
  • Exit the interactive shell
docker logs apacheserver
  • This will give you the log output of the container
  • You even see the request from inside the container
docker logs apacheserver -f
  • Will follow the log output until you hit ctrl+c
  • But still, http://localhost:80 doesn't do anything on the host

Let's have a look into the container details:

docker inspect apacheserver
  • Will print out the container information
  • You see there are no ports bound to the host
docker stop apacheserver
  • Stop and remove the container
  • You could also do docker rm -f apacheserver
docker ps -a
  • Should be empty

Docker Port Forwarding

docker run -d --rm --name apacheserver -p 8080:80 httpd
  • -p 8080:80 forwards HOST-PORT:GUEST-PORT
  • On the host machine port 8080 is now mapped to port 80 in the guest machine

Open http://localhost:8080

  • Should bring up now "it works"
docker inspect apacheserver
  • Now shows the forwarded port
docker stop apacheserver
  • Should stop and remove the container again

http://localhost:8080

  • Is again unreachable, because the server stopped
docker run -d --rm --name phpserver -p 8080:80 -v ${PWD}:/var/www/html php:7.2-apache
  • Starts a new container named "phpserver" and maps port 80 from the container onto port 8080 on the host
  • Maps the current directory into /var/www/html, which is the document-root for apache
  • If you still have the index.php there it will now be served on http://localhost:8080
docker stop phpserver
  • Let's remove the container and clean up
docker ps -a

Should be empty again.