Docker Deploy stack extra hosts ignored

2019-08-19 03:33发布

问题:

docker stack deploy isnt respecting the extra_hosts parameter in my compose file. when i do a simple docker-compose up the entry is created in the /etc/hosts however when i do docker deploy –compose-file docker-compose.yml myapp it ignores extra_hosts, any insights? Below is the docker-compose.xml:

version: '3'
services:
  web:
    image: user-service
    deploy:
      labels: 
       - the label
    build:
       context: ./
    environment:
      DATABASE_URL: jdbc:postgresql://dbhost:5432/postgres
    ports:
      - 9002:9002
    extra_hosts:
      - "dbhost: ${DB_HOST}"
    networks:
      - wellness_swarm
    env_file:
      - .env
networks:
  wellness_swarm:
    external:
      name: wellness_swarm

the docker-compose config also displays the compose file properly.

回答1:

This may not be a direct answer to the question as it doesn't use env variables but what I found was that the extra_hosts block in the compose file was ignored in swarm mode if entered in the format above.

i.e. this works for me and puts entries in /etc/hosts in the container:

    extra_hosts:
      retisdev: 10.48.161.44
      retistesting: 10.48.161.44

whereas when entered in the other format it gets ignored when deploying as a service

    extra_hosts:
      - "retisdev=10.48.161.44"
      - "retistesting=10.48.161.44"


回答2:

I think it's an ordering issue. The ${} variable you've got in the compose file runs during the YAML processing before the service definition is created. Then stack deploy processes the .env file for running in the container as envvars, but the YAML variable is needed first...

To fix that, you should use the docker-compose config command first, to process the YAML, and then use the output of that to send to the stack deploy.

docker-compose config will show you the output you're likely wanting.

Then do a pipe to get a one-liner.

docker-compose config | docker stack deploy -c - myapp

Note: Ideally you wouldn't use the extra_hosts, but rather put the envvar directly in the connection string. Your way seems like unnecessary complexity and isn't the usual way I see a connection string created.

e.g.

version: '3'
services:
  web:
    image: user-service
    deploy:
      labels: 
       - the label
    build:
       context: ./
    environment:
      DATABASE_URL: jdbc:postgresql://${DB_HOST}:5432/postgres
    ports:
      - 9002:9002
    networks:
      - wellness_swarm
    env_file:
      - .env
networks:
  wellness_swarm:
    external:
      name: wellness_swarm


回答3:

As i see https://github.com/moby/moby/issues/29133 seems like it is by design where in the compose command takes into consideration the environment variables mentioned in .env file however the deploy command ignores that :( why is that so, pretty lame reasons!