I have a RestAPI (TypeScript+Express) which connects to a MongoDB collection, if both of them are running in Docker's containers and I try to get data through an endpoint it retuns a JSON with no data, if I run the RestAPI in bare metal (Ubuntu) I get the expected data from MongoDB container. So far I've checked:
- expected ports in Listen Mode (passed)
- no firewall rules blocking communication (passed)
- No authentication required (passed)
- Status 200 and JSON generated (passed)
Below you can find an example of data retrieved (API running in bare metal):
The same example but this time the API running on a Docker's container:
The same endpoint with more details:
I've also tried to login to the API container and run the endpoint but still no data. One important fact is the connection parameters are managed though .env file; checking the logs file from each container everything seems to be normal.
Here you can find the Dockerfile of my API:
FROM node:18-alpine AS builder
WORKDIR /295fullstack
COPY ./backend/*.json ./
RUN apk add yarn
RUN apk add bash
RUN apk add curl
RUN yarn install --frozen-lockfile
COPY ./backend/. .
RUN yarn add dotenv
COPY ./backend/.env.template ./.env
RUN sed -i '1iNODE_ENV=development' ./.env
RUN sed -i 's/DATABASE_URL=.*$/DATABASE_URL=mongodb:\/\/mongodb:27017/' ./.env
RUN sed -i 's/DATABASE_NAME=.*$/DATABASE_NAME=TopicstoreDB/' ./.env
RUN sed -i 's/HOST=.*$/HOST=0.0.0.0/' ./.env
RUN sed -i 's/PORT=.*$/PORT=5000/' ./.env
#adding a script for loading env with Typescript
RUN sed -i '/"scripts": {/a\ "start:with-env": "ts-node -r dotenv/config src\/app",' package.json
EXPOSE 5000
CMD ["yarn", "run", "start:with-env"]
And this one is for the MongoDB:
FROM mongo:7.0.2
MAINTAINER @heftamayo
COPY db/mongo-initutf8.js /docker-entrypoint-initdb.d/
EXPOSE 27017
CMD ["mongod", "--bind_ip_all", "--port", "27017"]
Finally, these are the services from the docker-compose:
version: "3.8"
services:
db:
container_name: mongodb
restart: always
build:
context: .
dockerfile: Dockerfile.mongo
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
#command: mongod --bind_ip_all
healthcheck:
test: ["CMD", "bash", "-c", "mongosh --eval 'db.adminCommand(\"ping\")'"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s
networks:
network:
ipv4_address: 192.168.20.7
backend:
container_name: 295fsbe
restart: unless-stopped
depends_on:
db:
condition: service_healthy
image: hftamayo/295fs_be:stable-1.0.0
ports:
- "5000:5000"
networks:
network:
ipv4_address: 192.168.20.9
volumes:
mongodb_data:
networks:
network:
driver: bridge
ipam:
config:
- subnet: 192.168.20.0/24
So basically I ran out of ideas how to debug this, surely the issue is in the API's container but honestly I don't get it, your suggestions and comments will be valuable to find what's going on with this.
Thanks a lot