Consider this docker-compose configuration:
# docker-compose.yml
version: "3.7"
services:
app:
build: ./app
depends_on:
- db
- vpn
ports:
- "3001:3000"
db:
image: postgres
vpn:
build: ./vpn
cap_add:
- NET_ADMIN
Description
- The
appis accessed from the docker host via http://localhost:3001. - The
appneeds to connect to a postgresdb, which is the second container. - Also, the
appneeds to connect to an api, which is only available though a vpn. This is why a third container,vpn, establishes the required vpn connection.
Goal
The app container should should be able to reach the other services within this docker-compose environment, i.e. the db, and route the rest of its traffic through the vpn container, such that it can access the api behind the vpn tunnel.
What I've tried
I have tried to set the
network_modeof theapp:services: app: network_mode: "service:vpn"This routes all traffic of the
appcontainer through thevpn. With this, I can reach the api behind the vpn tunnel from theappcontainer. But this is not compatible withports: - "3001:3000". Also, thedbcontainer cannot be reached from theappanymore:ping: bad address 'db'.I also have tried to link the
dbcontainer from thevpncontainer, hoping that this would make thedbservice available to theapp.services: app: network_mode: "service:vpn" vpn: links: - dbBut still
dbcannot be found byapp.If I link the
dbcontainer from thevpncontainer but do not establish the vpn connection within thevpncontainer, thedbcontainer can be reached from theapp.And I've experimented with adding
127.0.0.1 dbto the/etc/hostsof theappcontainer, vaguely hoping that I could reach thedbport directly. But this also does not work.
Does anyone have a clue how to achieve this?