I have 2 docker containers (1 for database and 1 for app server). The app code has the host of the database in the connection string. I would like to be able to run the app without modifying any code (including connection string / host configuration).
My thought was to add something to the /etc/hosts file on the app container so the database host resolves to the other container but not sure what IP address I could set. The IP could be different every time I create the containers right? The below works sort of but I need something more permanent.
172.23.0.2 database.mycompany.com
would be cool if I could specify something like this in /etc/hosts
db-container-name database.mycompany.com
Edit: Lots of very helpful comments but the one thing being missed is I have a connection string in the codebase and I dont want to change the code:
<New class="oracle.jdbc.pool.OracleDataSource">
<Set name="URL">jdbc:oracle:thin:@db.mycompany.com:1532:SVC</Set>
</New>
If I want to use container name I would have to change the above config to the container name. Ive tested and it works but I cant check that in ever so I need something that doesnt change the code. The static IP address option mentioned below is probably my best bet and will confirm that answer once I can test it out.
Here is sample docker-compose.yml.
Check the static IP assignment below:
version: '3.8'
services:
nginx: <- DNS Name
image: nginx
container_name: qs
restart: always
ports:
- 80:80
volumes:
- ~/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- server01
networks:
nginx:
ipv4_address: 10.1.1.10 <- Static IP
networks:
nginx:
driver: bridge
ipam:
config:
- subnet: 10.1.1.0/24 <- Static IP subnet
By this you can eliminate the problem of dynamic IP
You can create multiple networks and assign as per you connection requirements.
networks:
nginx:
driver: bridge
ipam:
config:
- subnet: 10.1.1.0/24
db:
driver: bridge
ipam:
config:
- subnet: 10.0.0.0/24
Like here you can see that there are 2 networks, How I use this is my app container and nginx are on nginx network and my db and app are on db network. so my db is accessed by my customers only by accessing my app via nginx. And there is no need to open port to host for db because container-to-container connection require no port opening.