Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to port forward in Docker container?

I'd like to forward 8080 port to 80 with iptables in a Docker container. In the build I have an error message as you can see below.

Here is the Dockerfile:

FROM fedora
RUN whoami && \
 iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080

Here is the output:

[~]# docker build -t temp /home/edfromhadria/Documents/Docker/temp/.
Sending build context to Docker daemon 2.048 kB
Sending build context to Docker daemon 
Step 0 : FROM fedora
 ---> 834629358fe2
Step 1 : RUN whoami &&  iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
 ---> Running in 95046cf959bf
root
iptables v1.4.21: can't initialize iptables table `nat': Permission denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.
INFO[0001] The command [/bin/sh -c whoami &&  iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080] returned a non-zero code: 3 

Thank you in advance for any help you can provide.

like image 770
los.adrian Avatar asked Apr 03 '15 14:04

los.adrian


1 Answers

First, running an iptables command during the docker build process would never make sense; even if it worked, the iptables command only modifies the runtime configuration of your kernel. These changes would not persist on the Docker image and would not be available when starting a container.

Second, even if you are running the iptables container after starting a container (rather than when building a container), it will still fail because Docker containers by default do not have the necessary privileges to modify the iptables configuration (or modify networking in general, or mount filesystems, etc). You can start a container with the --privileged flag, but that is probably not what you want to do (because that confers a number of additional privileges on the container which are probably not necessary, and from a security perspective it's a good idea to only grant privileges that are absolutely necessary).

You would typically handle this using Docker's -p option to connect ports on your host to ports in your container, for example:

docker run -p 80:8080 temp

This would link port 80 on your host to port 8080 on the container.

If that's not what you want, an easier solution is just to configure the application in your container to run on the desired port.

like image 146
larsks Avatar answered Sep 19 '22 21:09

larsks