reactjs in docker building react
I have a problem I am building my reactjs app in a buildstep in docker and then using nginx to run it. However I can not get it to be able to connect to my api running in another container
The relevant parts of my docker-cmpose.yml are here
api:
build:
dockerfile: Dockerfile
context: "./api"
depends_on:
- mysql_db
volumes:
- /app/node_modules
- ./api:/app
environment:
<<: *common-variables
MYSQL_HOST_IP: mysql_db
networks:
- my-network
frontend:
depends_on:
- api
stdin_open: true
environment:
API_URL: http://api:3030/v1
build:
dockerfile: Dockerfile
context: ./frontend
ports:
- "8090:80"
volumes:
- /app/node_modules
- ./frontend:/app
networks:
- my-network
networks:
my-network:
name: my-network
The relevant bit from my Dockerfile is
COPY package.json ./
COPY ./ ./
RUN npm i && npm run build
# production environment
FROM nginx:stable-alpine
WORKDIR /app
COPY --from=build /app/build /usr/share/nginx/html
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
And finally in my default.conf for ngnx I have
upstream api {
server api:3030;
}
server {
listen 80;
listen [::]:80;
root /usr/share/nginx/html;
index index.html index.htm index.nginx-debian.html;
server_name xxxx.com www.xxxx.com
location / {
try_files $uri $uri/ =404;
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://api;
}
}
The problem I am having is it wont resolve to the api
Please can anyone help me to get it to resolve to the ip/url for the api running in its container?
Thanks in advance
The React application runs in a browser, and it can't use any of the Docker networking features. In particular, since it runs in a browser, it can't resolve the api
host name, which only exists in containers running on the same Compose network, and your browser isn't in a container.
You already have your Nginx setup to proxy /api
to the back-end application, and I'd just use that path. You can probably set something like API_URL: /api/v1
with no host part. Your browser will interpret this as a path-only relative URL and use the host and port the application is otherwise running on.