How to assign domain names to containers in Docker

2020-05-14 09:25发布

I am reading a lot these days about how to setup and run a docker stack. But one of the things I am always missing out on is how to setup that particular containers respond to access through their domain name and not just their container name using docker dns.

What I mean is, that say I have a microservice which is accessible externally, for example: users.mycompany.com, it will go through to the microservice container which is handling the users api

Then when I try to access the customer-list.mycompany.com, it will go through to the microservice container which is handling the customer lists

Of course, using docker dns I can access them and link them into a docker network, but this only really works for wanting to access container to container, but not internet to container.

Does anybody know how I should do that? Or the best way to set that up.

2条回答
SAY GOODBYE
2楼-- · 2020-05-14 10:04

For all I know, Docker doesn't provide this feature out of the box. But surely there are several workarounds here. In fact you need to deploy a DNS on your host that will distinguish the containers and resolve their domain names in dynamical IPs. So you could give a try to:

  1. Deploy some of Docker-aware DNS solutions (I suggest you to use SkyDNSv1 / SkyDock);

  2. Configure your host to work with this DNS (by default SkyDNS makes the containers know each other by name, but the host is not aware of it);

  3. Run your containers with explicit --hostname (you will probably use scheme container_name.image_name.dev.skydns.local)

You can skip step #2 and run your browser inside container too. It will discover the web application container by hostname.

查看更多
萌系小妹纸
3楼-- · 2020-05-14 10:06

So, you need to use the concept of port publishing, so that a port from your container is accessible via a port from your host. Using this, you can can setup a simple proxy_pass from an Nginx that will redirect users.mycompany.com to myhost:1337 (assuming that you published your port to 1337)

So, if you want to do this, you'll need to setup your container to expose a certain port using:

docker run -d -p 5000:5000 training/webapp # publish image port 5000 to host port 5000

You can then from your host curl your localhost:5000 to access the container.

curl -X GET localhost:5000

If you want to setup a domain name in front, you'll need to have a webserver instance that allows you to proxy_pass your hostname to your container.

i.e. in Nginx:

server {
  listen 80;
  server_name users.mycompany.com;
  location / {
    proxy_pass http://localhost:5000;
  }
}

I would advise you to follow this tutorial, and maybe check the docker run reference.

查看更多
登录 后发表回答