I am dockerizing a strapi application with mongodb atlas hosted database. The image is working fine when I am hardcoding the database credentials inside config/database.js file. But I want to get those credentials from .env file. According to strapi doc I can get those variable in database.js file without using the dotenv package
But this shows me the following error
error Error connecting to the Mongo database. URI does not have hostname, domain name and tld
I tried to use dotenv and used process.env to get variables but it still shows me the same erro. Any idea how can I resolve this?
database connection code
require('dotenv').config()
const {
DATABASE_HOST,
DATABASE_USERNAME,
DATABASE_PASSWORD
} = process.env;
module.exports = ({ env }) =>
({
defaultConnection: 'default',
connections: {
default: {
connector: 'mongoose',
settings: {
host: env('DATABASE_HOST', 'open-jade-cms-0.r07jc.mongodb.net'),
srv: env.bool('DATABASE_SRV', true),
port: env.int('DATABASE_PORT', 27017),
database: env('DATABASE_NAME', 'open-jade-cms-dev'),
username: env('DATABASE_USERNAME', 'open-jade-data-admin'),
password: env('DATABASE_PASSWORD', 'uppERH7xmydTpXI8')
},
options: {
authenticationDatabase: env('AUTHENTICATION_DATABASE', null),
ssl: env.bool('DATABASE_SSL', true),
},
},
},
});
docker file
FROM strapi/base
COPY ./ ./
RUN npm install
RUN npm install dotenv
RUN npm run build
CMD ["npm","run", "start:develop"]
You won't need to install dotenv
package. Just make sure you have .env
in place. Something like this:
DATABASE_CLIENT=mongo
DATABASE_NAME=strapi
DATABASE_HOST=mongoexample
DATABASE_PORT=27017
DATABASE_USERNAME=strapi
DATABASE_PASSWORD=password
MONGO_INITDB_ROOT_USERNAME=strapi
MONGO_INITDB_ROOT_PASSWORD=password
It is a good idea to use docker-compose when running strapi locally
version: "3"
services:
strapiexample:
image: strapi/strapi
container_name: strapiexample
restart: unless-stopped
env_file: .env
environment:
DATABASE_CLIENT: ${DATABASE_CLIENT}
DATABASE_NAME: ${DATABASE_NAME}
DATABASE_HOST: ${DATABASE_HOST}
DATABASE_PORT: ${DATABASE_PORT}
DATABASE_USERNAME: ${DATABASE_USERNAME}
DATABASE_PASSWORD: ${DATABASE_PASSWORD}
networks:
- strapi-app-network
volumes:
- ./app:/srv/app
ports:
- "1337:1337"
The above has been taken from strapi blogs