How to Add Authentication to MongoDB in Portainer (Docker)

MongoDB doesn’t use any authentication by default. Make sure you change this before you use your database in production.

Marvin Wendt
Mar 3 · 2 min read
Image for post
Image for post
Photo by Croissant on Unsplash

MongoDB doesn’t use any authentication by default. This should be changed when opening the database to the internet.

In this article, I’ll describe how you can enable authentication for MongoDB inside Portainer — a web interface for Docker.

Add Authentication to MongoDB

  1. Open your Portainer interface.
  2. If you haven’t already, install MongoDB. (You can do this via the app templates on Portainer.)
  3. Go into the console of your MongoDB container.
Image for post
Image for post
Image for post
Image for post

4. Write mongo into the console.

Image for post
Image for post

5. Change to the admin database.

> use admin

6. Create a new user.

> db.createUser(
{
user: "nameHere",
pwd: "passwordHere",
roles: [ { role: "root", db: "admin" } ]
}
)

If you want to paste the snippet above, copy it to an editor first and fill the fields there — it’ll be a lot easier. Also, if you want to paste it into the Portainer console, you’ll have to do a right-click and select paste.

The root user is created now.

Tell MongoDB to Start With the Authentication

1. Go to the Duplicate/Edit section of your MongoDB container.

Image for post
Image for post

2. Set your Command to 'mongod' '--auth'.

Image for post
Image for post

3. Deploy the container.

Image for post
Image for post

Conclusion

Your whole MongoDB is now using a username/password authentication!

Thanks for reading.

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store