Docker Stack Deploy忽略extra_hosts参数问题求助
Hey there, let's figure out why extra_hosts works with docker-compose up but gets ignored when deploying to Docker Swarm with docker deploy.
First, the core issue: Docker Swarm doesn't support the root-level extra_hosts field in Compose files—this is a deliberate limitation of the Swarm orchestrator, since it manages container networking differently than standalone Compose. Standalone Compose runs containers on a single node, so adding host entries is straightforward, but Swarm has to coordinate across multiple nodes, which changes how network configurations are handled.
Here are your practical solutions to get those host entries working in Swarm:
1. Manually add hosts via service update
After deploying your stack, you can directly update the service to inject the host entry using the docker service update command. This is quick for one-off changes:
docker service update --add-host dbhost:<YOUR_DB_IP_ADDRESS> myapp_web
This will push the host entry to all running containers in the myapp_web service, and any new containers created by Swarm will inherit it too.
2. Use a custom /etc/hosts file via Docker Config
If you want to bake the host entry into your stack definition (so it's reproducible across deployments), use Docker Config to mount a custom hosts file into your containers. Here's how:
- First, create a
custom_hostsfile that includes both the default container hosts entries and your newdbhostline (don't skip the defaults—otherwise your container will lose critical entries likelocalhost):127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters <YOUR_DB_IP> dbhost - Create a Docker Config from this file:
docker config create custom_hosts ./custom_hosts - Update your
docker-compose.ymlto mount this config as the container's/etc/hosts:version: '3.8' # Use a newer Compose version that supports configs properly services: web: image: user-service deploy: labels: - "the label" build: context: ./ environment: DATABASE_URL: jdbc:postgresql://dbhost:5432/postgres ports: - 9002:9002 configs: - source: custom_hosts target: /etc/hosts configs: custom_hosts: external: true # We created this config manually outside the stack
Now when you deploy with docker deploy, the container will use your custom hosts file with the dbhost entry.
3. Use Swarm's built-in service discovery (if applicable)
If dbhost is another service running in your Swarm cluster, you don't need extra_hosts at all! Swarm has built-in DNS that lets you reference services by their name directly. For example, if your database service is named db, just update your DATABASE_URL to:
DATABASE_URL: jdbc:postgresql://db:5432/postgres
Swarm will automatically resolve db to the database service's containers.
内容的提问来源于stack exchange,提问作者vaibhav

