Martin's Tex-Blog

Posts on programming and generally technical topics

Archive for September 2017

Docker: how to curl from one container into another

leave a comment »


I have a docker compose file that is similar to the following one:

version: "3"
services:
    web:
        image: nginx
        ports:
            - "80:80"
        volumes:
            - ./volumes/www/app1.example.com/html:/var/www/app1.example.com/html:z
            - ./volumes/www/app2.example.com/html:/var/www/app2.example.com/html:z
            - ./volumes/www/app3.example.com/html:/var/www/app3.example.com/html:z
        restart: always
    cron:
      build:
        context: .
        dockerfile: cron-dockerfile
      links:
        - php
        - web
    php:
      # unimportant
    db:
      # unimportant

as you see I have a web container with nginx serving webpages from three virtual hosts. For each I have a domain name specific to application name. I also have a cron container which is supposed to do some maintance jobs from time to time. It does it by executing some php script on web server. Before migrating to docker I used basicly:

 curl http://app1.example.com/some_maintance.php 

But with docker I always get host unreachable error.

After some investigation I found that I am able to ping app1.example.com from cron container but curl or wget does not reach it, also web which is supposed to be a link to nginx container from cron container has different ip than actual app1.example.com (for which I have registrated domain with physical ip address). I have access to any other domain names – http://www.google.com etc. is accessible by curl.

So the first solution I tried was to update \etc\hosts on cron container, I added 1.2.3.4 app1.example.com entry, where 1.2.3.4 is IP address of web container. And it worked. The problem is that from what I know modifying \etc\hosts is not encouraged by docker community. Instead you should use extra_hosts in docker compose yaml file, but you can specify in extra_hosts only explicit IP addresses, you cannot use container name (like web in my configuration). From what I know, if you need such feature then it is a sign you should start using custom networks. I tried to use custom networks but unfortunately with no luck.

Finally what worked was to make curl use IP address of my web container (where I can put web), and then pass domain name as -H parameter. So the command looks as follows:

curl -H'Host: app1.example.com' web/some_maintance.php
Advertisement

Written by Marcin

September 19, 2017 at 3:48 pm

Posted in Uncategorized

Tagged with