mongodb docker in linux (ubuntu)

First things first, install docker snap by Canonical in the App Store on Ubuntu.

To start a MongoDB Docker container in Linux, run the following docker run command in your terminal:

docker run -d \
  --name my-mongodb \
  -p 27017:27017 \
  -v mongodb_data:/data/db \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=secretpassword \
  mongo:latest

(Note: If you get a permission error, prepend sudo to the command.)

What this command does:

Useful Follow-Up Commands

Connecting to local NodeJS application

To connect your Node.js application to your MongoDB Docker container, use the mongodb or mongoose npm packages with a standard connection string. Because the Docker container maps port 27017 to your Linux host, your Node app can talk to it using localhost (if the Node app is running directly on your host machine).

Here is the exact connection string based on the credentials used in the previous step:

mongodb://admin:secretpassword@localhost:27017/mydatabase?authSource=admin

Step-by-Step Implementation

In your Node.js project folder, install Mongoose (or the native MongoDB driver):

npm install mongoose

Create or update your server file (e.g., index.js or server.js) with the following clean connection snippet:

const mongoose = require('mongoose');

// Best practice: Use environment variables for the URI
const MONGO_URI = process.env.MONGO_URI || 'mongodb://admin:secretpassword@localhost:27017/mydatabase?authSource=admin';

mongoose.connect(MONGO_URI)
  .then(() => console.log('🚀 Successfully connected to MongoDB Docker container!'))
  .catch((err) => console.error('❌ MongoDB connection error:', err));

Critical Troubleshooting Steps

If your application throws a MongooseServerSelectionError or fails to connect, verify these three settings:


created: 31 Oct 2026