I've got a Node API dockerized that is working fine when accessed from Postman and the VueJs front (frontend is not in Docker).
I've now spun up another Node project in Docker but can't seem to access the API of the main project.
I'm trying to call the API via Axios. Based on the setup I have, I thought the baseUrl to connect to the main API would be:
http://boodil-payments-api:8080
Here's what the docker-compose.yml looks like
docker-compose for the main project
version: "3.9"
networks:
boodil-network:
driver: bridge
volumes:
boodil-mysql:
services:
api:
container_name: boodil-payments-api
build: .
working_dir: /app
volumes:
- ./:/app:ro
- /app/node_modules
ports:
- "2000:8080"
depends_on:
- mysql
networks:
- boodil-network
environment:
- NODE_ENV=development
command: npm run dev
mysql:
container_name: mysql
image: mysql:8.0.31
restart: always
environment:
MYSQL_ROOT_PASSWORD: password
ports:
- "3307:3306"
volumes:
- boodil-mysql:/var/lib/mysql
networks:
- boodil-network
docker-compose for the second project
version: "3.9"
networks:
boodil-network:
driver: bridge
services:
api:
container_name: boodil-demo-api
build: .
working_dir: /app
volumes:
- ./:/app:ro
- /app/node_modules
ports:
- "2001:8080"
networks:
- boodil-network
environment:
- NODE_ENV=development
command: npm run dev
They both have identical Dockerfile's
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD [ "npm", "start" ]
CodePudding user response:
As is, your two compose projects are using totally different networks and one cannot see the other. Unless you give a custom name, docker compose creates a network named <compose_project_name>_<compose_network_reference_name>
and will refuse to create two identical compose managed network (i.e. same project and reference name).
The first thing to do to ease your life is to create a network in your first project which as a well know and predetermined name. This is done by customizing your network with a custom name (i.e. the one you can see in the output of docker network ls
):
# In project #1
networks:
boodil-network:
driver: bridge
name: boodil-network
Now that we have an easy name to remember, we can use this network as an external network in other compose projects. This means that the network is expected to exist prior to starting the services in that project and won't be managed by docker compose on up and down events.
# In project #2
networks:
boodil-network:
name: boodil-network
external: true
And from there, your second project will be able to access the api in your first project by using either its service name (api:8080
) or container name (boodil-payments-api:8080
)
Note that you will need to rename your service in your second project (e.g. api
=> api2
....) as it will conflict with the existing service from your other project on the same network.
Reference: Docker compose networking documentation