Reputation: 389
Lets suppose that I have got a ten services in docker-compose and every this service need the same extra_hosts with a four records. I would like to define extra_hosts once and only include it to every service.
Is it possible?
version: '3.7'
services:
web:
build:
context: ./apache
dockerfile: dockerfile_apache2
image: debian:latest
container_name: hsthttp1
extra_hosts:
- "somehost1:162.242.195.82"
- "somehost2:162.242.195.83"
- "somehost3:162.242.195.84"
- "somehost4:162.242.195.85"
web2:
build:
context: ./apache
dockerfile: dockerfile_apache2
image: debian:latest
container_name: hsthttp2
extra_hosts:
- "somehost1:162.242.195.82"
- "somehost2:162.242.195.83"
- "somehost3:162.242.195.84"
- "somehost4:162.242.195.85"
web3:
build:
context: ./apache
dockerfile: dockerfile_apache2
image: debian:latest
container_name: hsthttp3
extra_hosts:
- "somehost1:162.242.195.82"
- "somehost2:162.242.195.83"
- "somehost3:162.242.195.84"
- "somehost4:162.242.195.85"
Upvotes: 1
Views: 5262
Reputation: 31644
Yes, it's possible to use Extension fields to define reusable fragments since compose version 3.4:
For your situation, you can use next:
docker-compose.yaml:
version: '3.7'
x-extra_hosts:
&default-extra_hosts
- "somehost1:162.242.195.82"
- "somehost2:162.242.195.83"
- "somehost3:162.242.195.84"
- "somehost4:162.242.195.85"
services:
web:
image: debian:latest
container_name: hsthttp1
extra_hosts: *default-extra_hosts
web2:
image: debian:latest
container_name: hsthttp2
extra_hosts: *default-extra_hosts
web3:
image: debian:latest
container_name: hsthttp3
extra_hosts: *default-extra_hosts
Above, we define a global &default-extra_hosts
which later in every service we can reference it with *default-extra_hosts
.
You can use docker-compose config
to quick check the effect as next:
shubuntu1@shubuntu1:~/try$ docker-compose config
services:
web:
container_name: hsthttp1
extra_hosts:
- somehost1:162.242.195.82
- somehost2:162.242.195.83
- somehost3:162.242.195.84
- somehost4:162.242.195.85
image: debian:latest
web2:
container_name: hsthttp2
extra_hosts:
- somehost1:162.242.195.82
- somehost2:162.242.195.83
- somehost3:162.242.195.84
- somehost4:162.242.195.85
image: debian:latest
web3:
container_name: hsthttp3
extra_hosts:
- somehost1:162.242.195.82
- somehost2:162.242.195.83
- somehost3:162.242.195.84
- somehost4:162.242.195.85
image: debian:latest
version: '3.7'
Upvotes: 10