skip to Main Content

I need to be able to run within the same container both: my nodejs server.js and mongodb.

I know it is possible to achieve this with docker-compose or with two separate containers but that is not an option here. I need both services running on the same container.

My Dockerfile is something like this:

FROM node:16
WORKDIR /usr/src/app
RUN apt-get update && apt-get install -y mongodb
COPY package.json ./
RUN npm install
COPY server.js public/ ./
EXPOSE 3000
EXPOSE 27017
CMD service mongodb start && node server.js

Then at some point my server.js needs to call the mongodb like this:

const uri = 'mongodb://172.0.0.1:27017';

However when I try to build my container I get:

E: Package 'mongodb' has no installation candidate

2

Answers


  1. I don’t know why would you want to do this, you can create two different Dockerfiles as well, but anyway.

    FROM node:16
    
    # Install MongoDB
    RUN apt-get update && 
        apt-get install -y wget gnupg && 
        wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | apt-key add - && 
        echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/5.0 main" | tee /etc/apt/sources.list.d/mongodb-org-5.0.list && 
        apt-get update && 
        apt-get install -y mongodb-org
    
    WORKDIR /usr/src/app
    
    COPY package.json ./
    RUN npm install
    
    COPY server.js public/ ./
    
    EXPOSE 3000
    EXPOSE 27017
    
    CMD service mongod start && node server.js
    
    const uri = 'mongodb://localhost:27017';
    
    Login or Signup to reply.
  2. Not sure why you are trying to run both MongoDB and Application in same container, Anyway you can do it like this;

    FROM node:14
    
    # Install MongoDB
    RUN apt-get update 
        && apt-get install -y mongodb 
    
    # Create a directory to hold the application code inside the image
    WORKDIR /usr/src/app
    
    # Copy the application code into the container at /usr/src/app
    COPY . .
    
    # Install npm packages
    RUN npm install
    
    EXPOSE 80
    
    # Run mongod to start MongoDB and server.js with Node.js in the background
    CMD mongod --fork --logpath /var/log/mongod.log && node server.js
    

    I’ve used mongoose NPM Package to connect to MongoDB,

    const mongoose = require('mongoose');
    
    const mongoDBUri = 'mongodb://localhost:27017/mydatabase';
    
    mongoose.connect(mongoDBUri, { useNewUrlParser: true, useUnifiedTopology: true });
    
    const db = mongoose.connection;
    
    db.on('error', console.error.bind(console, 'MongoDB connection error:'));
    db.once('open', function() {
      console.log('Connected successfully to MongoDB');
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search