Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

node.js - Node/Express API gets no data from mongodb when i use Docker

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...