I'm building a website using a Django backend and a Vuejs frontend . I develop using docker-compose which works great. The only thing is that my frontend needs to call the backend container, which I currently do by hardcoding the container ip address in the Javascript:
const API_HOST = '192.168.0.105';
const API_ADDRESS = `http://${COCKPIT_SERVER_HOST}:8000/cockpit`;
This works, but it's obviously not the right way to do it. Sometimes the ip address of the backend container changes which makes me lookup the new ip address again.
In my docker-compose.yml
file I named the backend api
(I pasted my docker-compose file below). But if I define API_HOST
in the Javascript as
const API_HOST = 'api';
it obviously doesn't work because that is called from within the browser, which is unaware of the Docker network.
How can I make the frontend always call the correct backend, without the need to constantly lookup the container ip address?
My docker-compose file:
version: '3'
services:
db:
image: postgres
ports:
- 5432:5432
environment:
POSTGRES_DB: cockpit
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
api:
build: server
volumes:
- ./server:/code
ports:
- 8000:8000
depends_on:
- db
command: >
bash -c '
python manage.py makemigrations &&
python manage.py migrate &&
python manage.py runserver 0.0.0.0:8000'
frontend:
build: client
volumes:
- ./client:/usr/src/app
- /usr/src/app/node_modules
ports:
- 8080:8080
depends_on:
- api
I would consider 2 solutions:
1. Static IP addresses
In docker-compose you can assign static IPs for each service.
Pros: Easy to implement
Cons: Hardcoded IP adresses in your code
version: '3'
services:
db:
image: postgres
ports:
- 5432:5432
environment:
POSTGRES_DB: cockpit
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
networks:
test:
ipv4_address: 172.28.2.1
api:
build: server
volumes:
- ./server:/code
ports:
- 8000:8000
depends_on:
- db
command: >
bash -c '
python manage.py makemigrations &&
python manage.py migrate &&
python manage.py runserver 0.0.0.0:8000'
networks:
test:
ipv4_address: 172.28.2.2
frontend:
build: client
volumes:
- ./client:/usr/src/app
- /usr/src/app/node_modules
ports:
- 8080:8080
depends_on:
- api
networks:
test:
ipv4_address: 172.28.2.3
networks:
test:
ipam:
driver: default
config:
- subnet: 172.28.0.0/16
2. Reverse proxy
As Keith suggested you can setup a reverse proxy (via ngnix or similar) to resolve your calls to services.
Pros: Good approach with no hardcoding
Cons: Additional service in your compose file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.