Docker port forwarding between container and host

2019-02-16 02:15发布

I'm new at docker and I'm trying to test some things. From the docs I saw that we can map ports between the container and the host.

So I pull the mariadb repo and run a container like this

$ docker run -p 127.0.0.1:3307:3306 --name mdb -e MYSQL_ROOT_PASSWORD=docker -d mariadb

This would bind port 3306 inside the container to port 3307 on the localhost or 127.0.0.1 interface on the host machine.

And It creates the container, I check it with $ docker ps

CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                      NAMES
f7d30562194c        mariadb             "/docker-entrypoint.   About an hour ago   Up 6 minutes        127.0.0.1:3307->3306/tcp   mdb

But when I telnet to the port, I got nothing

$ telnet 127.0.0.1 3307
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
telnet: Unable to connect to remote host

I'm doing this becouse I've got a mysql running in the 3306 port, and I don't want to mess with that. I try switching the orders on the -p option and also nothing on the telnet. Can you help me to see what I'm doing wrong?

(Also I'm running over boot2docker on OSX 10.9.5)

标签: docker
2条回答
闹够了就滚
2楼-- · 2019-02-16 02:44

If you are using boot2docker, that means you need to forward that port at the VM level itself:

VBoxManage controlvm boot2docker-vm natpf1 "name,tcp,127.0.0.1,3307,,3307"

See:

查看更多
太酷不给撩
3楼-- · 2019-02-16 02:51

The basic problem is that if you're using boot2docker, you need to address localhost on the boot2docker VM, not the Mac.

To make the problem clear, this should work:

$ boot2docker ssh
...
$ docker run -p 127.0.0.1:3307:3306 --name mdb -e MYSQL_ROOT_PASSWORD=docker -d mariadb
...
$ telnet 127.0.0.1 3307

But obviously you don't want to ssh into the VM each time. So I would just replace 127.0.0.1 with the IP of the boot2docker VM and you're done:

$ telnet $(boot2docker ip) 3307
查看更多
登录 后发表回答