Docker: Your First MongoDB Connection in 10 mins

Web development Jul 4, 2023

Docker

This is the command to run

// Without password
$ docker run --name my-mongo -p 27017:27017 -d mongo
// With password
$ docker run --name my-mongo \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=root \
-e MONGO_INITDB_ROOT_PASSWORD=example \
-d mongo

Then check the process with docker ps

Docker Compose

When use compose we put the long command to docker-compose.yml file.

If you don’t need password just leave the environment: block
version: '3.1'
services:
mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example

Then run the docker-compose up

MongoDB Connection

From Docker

$ docker exec -it my-mongo mongo

From CLI: mongo

Step 1: Installation

The shell login needs mongo command line which is in the mongo-org packages.

Fedora/Red Hat: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/

Ubuntu: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

Step 2: Test port open

Then you can test the connection with

$ netcat -vz localhost 27017

The output should show success port is opened.

Step 3: Connecting

Then you can connect with the command

$ mongo
// without password$ mongo -u root -p
// with password

Test with some command:

$ use test-db
$ db.texts.insert({ title: 'hello world' })// Check the result
$ db.texts.find()
$ show dbs$ show collections// Working

Hope this helps

Cheers!

Tags

TeamCMD

We are CODEMONDAY team and provide a variety of content about Business , technology, and Programming. Let's enjoy it with us.