DEV Community

Cubite
Cubite

Posted on

1

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 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
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
corpcubite profile image
Cubite •

Thank you Nico. Agree, unfortunatly the services were installed by a third party for our customer and they didn't feel comfortable with removing the container and creating new one. We check the DOCKER-USER and update the post.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more