I build a simple REST API with Node/Express which have routes which fetch data from MongoDB Atlas.
running it on localhost works & localhost via ngrok works fine
But as soon as i try to dockerize it i didn't get it working
First i tried to build a container based on node:15-alpine -> i couldn't even get it to start
Then i tried the standard node:15 base, there the container starts and i get the message, that the DB is connected, but each response is an empty array.
Current Dockerfile
FROM node:15
#set working directory
WORKDIR /usr/src/app
#copy all package json files to the working directory
COPY package*.json ./
#install dependencies
RUN npm install
#copy all the rest of the app to the working directory
COPY . .
#open port 3000
EXPOSE 3000
#start app
CMD ["npm", "start"]
Docker run command
docker run --rm -it --name api -p 3000:3000 --env DB_CONNECTION=mongodb+srv://****:*****@*****.mongodb.net/
simpleAPI?retryWrites=true"&"w=majority api
app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv").config();
const cors = require("cors");
//middleware express json parser for every request
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
//import routes
const wordRoute = require("./routes/words");
//use routes as middleware
app.use("/words", wordRoute);
//connect to db
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("connected to mongoDB");
}
);
app.listen(3000);
Any idea? Would be great :-)
question from:
https://stackoverflow.com/questions/65906774/node-express-api-gets-no-data-from-mongodb-when-i-use-docker 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…