Map running container port to the Host

We recently ran to a situation that we have a running container (MySQL) but we liked to access it from internet and this container didn’t have any port mapping between host and container.

We spawn up the container with docker compose

One solution …

We recently ran to a situation that we have a running container (MySQL) but we liked to access it from internet and this container didn’t have any port mapping between host and container.

We spawn up the container with docker compose

One solution for this situation is to stop the container, remove it and execute docker run with -p <hostPort>:<containerPort> but we didn’t want to create new container.
Second solution is using iptables to do the port mapping.
In the following example, you see how we achieved routing calls to the host:3306 to the mysqlContainer:3306.
You should run this on the host machine.

sudo iptables -t nat -A DOCKER -p tcp --dport 3306 -j DNAT --to-destination MysqlContainerIP:3306
sudo iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp --source MysqlContainerIP --destination MysqlContainerIP --dport 3306
sudo iptables -A DOCKER -j ACCEPT -p tcp --destination MysqlContainerIP --dport 3306

Print Share Comment Cite Upload Translate
APA
Cubite | E-learning Solutions | Sciencx (2024-03-28T10:42:40+00:00) » Map running container port to the Host. Retrieved from https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/.
MLA
" » Map running container port to the Host." Cubite | E-learning Solutions | Sciencx - Saturday July 3, 2021, https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/
HARVARD
Cubite | E-learning Solutions | Sciencx Saturday July 3, 2021 » Map running container port to the Host., viewed 2024-03-28T10:42:40+00:00,<https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/>
VANCOUVER
Cubite | E-learning Solutions | Sciencx - » Map running container port to the Host. [Internet]. [Accessed 2024-03-28T10:42:40+00:00]. Available from: https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/
CHICAGO
" » Map running container port to the Host." Cubite | E-learning Solutions | Sciencx - Accessed 2024-03-28T10:42:40+00:00. https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/
IEEE
" » Map running container port to the Host." Cubite | E-learning Solutions | Sciencx [Online]. Available: https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/. [Accessed: 2024-03-28T10:42:40+00:00]
rf:citation
» Map running container port to the Host | Cubite | E-learning Solutions | Sciencx | https://www.scien.cx/2021/07/03/map-running-container-port-to-the-host/ | 2024-03-28T10:42:40+00:00
https://github.com/addpipe/simple-recorderjs-demo