Setting up MongoDB within a Docker container for local development

Tom Szpytman
1 min readMay 28, 2021

--

Step 1: Install Docker on your local machine

See the fantastic set of instructions here.

Step 2: Set up a MongoDB Docker container

Pull down the pre-built mongo image from the Docker repository:

docker pull mongo

Start a Docker container:

docker run
-d
--name YOUR_CONTAINER_NAME_HERE
-p YOUR_LOCALHOST_PORT_HERE:27017
-e MONGO_INITDB_ROOT_USERNAME=YOUR_USERNAME_HERE
-e MONGO_INITDB_ROOT_PASSWORD=YOUR_PASSWORD_HERE
mongo

Check that the container’s up and running:

docker container ls

(you should see your container listed)

Step 3: Connect to the container and access your MongoDB instance

Start + connect to a bash shell within the container:

docker exec -it YOUR_CONTAINER_NAME_HERE bash

Access the MongoDB instance via the mongo command line interface:

mongo --username YOUR_USERNAME_HERE --password YOUR_PASSWORD_HERE

List all databases:

show dbs

Step 4: Connecting to the database from outside of the container

You can use a Mongo client to connect to the database directly from your local machine using the URI:

mongodb://YOUR_USERNAME_HERE:YOUR_PASSWORD_HERE@0.0.0.0:YOUR_LOCALHOST_PORT_HERE/

--

--

Tom Szpytman
Tom Szpytman

Written by Tom Szpytman

Full-stack + Product. Available for hire either as an independent contractor, or as part of a voliyo.dev team. Inquiries: mail [at] voliyo.dev.