Introduction
In the first article here we discussed about how we can generate a x.509 certificate for secure connection to MongoDB. In this article we will implement these certificate files into docker MongoDB container.
Configuring MongoDB docker container instance with the x.509 certificate.
mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/server.pem
CAFile: /etc/ssl/ca.crt
security:
authorization: enabled
clusterAuthMode: x509
MongoDB Dockerfile
# Use the official MongoDB Docker image as base
FROM mongo:latest
# Port for MongoDB to run on
EXPOSE 27017
# Update the image and install the Vim package
RUN apt-get update && \
apt-get install -y vim && \
rm -rf /var/lib/apt/lists/*
# Copy certificates to the container
COPY ./crt/server.pem /etc/ssl
COPY ./crt/client.pem /etc/ssl
COPY ./crt/ca.crt /etc/ssl
# Copy the configuration file to the container
COPY mongod.conf /etc/mongod.conf
RUN echo "********************************************************"
# Start MongoDB with custom configuration
CMD ["mongod", "--config", "/etc/mongod.conf"]
docker-compose.yml
version: "3"
services:
mongo:
build: ./mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
volumes:
- ./mongodata:/data/db
- ./mongo/cert:/cert
ports:
- 27017:27017
volumes:
mongodata:
directory structure
.
├── mongo
│ ├── crt
│ ├── Dockerfile
│ └── mongod.conf
├── ubuntu
│ ├── crt
│ │ ├── ca.key
│ │ ├── ca.srl
│ │ ├── client.crt
│ │ ├── client.csr
│ │ ├── client.key
│ │ ├── server.crt
│ │ ├── server.csr
│ │ └── server.key
│ └── Dockerfile
├── .gitignore
└── docker-compose.yml
Copy the certificate files from the /ubuntu/crt folder to the /mongo/crt folder.
The new directory structure after copying the certificate files:
.
├── mongo
│ ├── crt
│ │ ├── ca.crt
│ │ ├── client.pem
│ │ └── server.pem
│ ├── Dockerfile
│ └── mongod.conf
├── ubuntu
│ ├── crt
│ │ ├── ca.key
│ │ ├── ca.srl
│ │ ├── client.crt
│ │ ├── client.csr
│ │ ├── client.key
│ │ ├── server.crt
│ │ ├── server.csr
│ │ └── server.key
│ └── Dockerfile
├── .gitignore
└── docker-compose.yml
run/up docker compose
docker compose up
docker ps --all
output
CONTAINER ID IMAGE PORTS NAMES
aa8e5b6a87af root-mongo ... root-mongo-1
182e54aeeca1 ubuntu-custom ubuntu1
exec root-mongo-1
docker exec -it root-mongo-1 bash
output
root@aa8:/#
Accessing a MongoDB instance secured with the x.509 certificate through Mongosh
Run mongosh with certificates parameters to connect mongoDB
mongosh --host localhost --tls \
--tlsCertificateKeyFile /etc/ssl/client.pem \
--tlsCAFile /etc/ssl/ca.crt
output
Using MongoDB: 7.0.1
Using Mongosh: 1.10.6
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
test>
Conclusion
In this article, we established a successful x.509 certificate tls connection to MongoDB using the previously generated mongodb-cert.key and mongodb.pem x.509 certificate files.
Top comments (0)