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
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
- 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
- Should bring up now āit worksā
docker inspect apacheserver
- Now shows the forwarded port
docker stop apacheserver
- Should stop and remove the container again
- 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.
Last updated on