i made a docker container for react app and another for django app . now when i make a websocket call
const socket = new WebSocket(
// `ws://${WEB_SOCKET}:${WEB_SOCKET_PORT}/ws/lobby/`//this works when i feed ip of django app
'wss://backend:8000/ws/lobby/'
);
it says
home.jsx:9 WebSocket connection to 'wss://backend:8000/ws/lobby/' failed:
here is docker-compose.yml file
services:
django-backend:
container_name: backend
restart : always
build:
context: ./server
ports:
- "8000:8000"
depends_on:
- postgres
- redis
volumes:
- ./server:/app
.
.
chess-frontend:
container_name: frontend
restart : always
build:
context: ./chess-front
target: development
ports:
- "5173:5173"
volumes:
- ./chess-front:/usr/src/app
presently i am checking ip of django container and manually updating the web socket url .my question is
- is there a way to make websocket url using domain name (ie. container name )
- if not can i automatically get django container’s ip in docker-compose up and update in url .
2
Answers
after research i found that web socket urls with domain name of host container do not resolve into ip of host container , even if they are in same network.
check this stack overflow thread
however i came up with a way to automatically update the ip of host container by running bash script before the frontend container starts . This fetches ip of backend container and updates my .env file variable
Dockerfile of react app
update_env.sh
docker-compose.yml
now whenever container restarts , i get ip of backend container automatically.
In Docker, containers can be accessed by their names within the same network.
You can create a network using the docker network create command.
For example:
docker network create my-network
Then, when you run your containers, add them to the network using the –network flag.
For example:
docker run –name backend –network my-network
YML update would be to specify networks as per below.
Remember to replace the port numbers (8000 and 5173) with the actual ports used by your backend and frontend services, respectively.