Docker:MongoDB初始化脚本:从.env文件读取值

l7mqbcuq  于 2023-02-18  发布在  Docker
关注(0)|答案(3)|浏览(179)

如何读取mongo-init.js中的env变量?docker-compose.yml可以从.env文件读取,但mongo-init.js不能,因为mongo-init.js将复制到/docker-entrypoint-initdb.d卷(不确定我是对是错)。这意味着mongo-init.jsprocess.env.MONGODB_USERNAME读取为undefined
在复制到/docker-entrypoint-initdb.d之前,是否可以先将env值转换为mongo-init.js
docker-compose.yml

version: '2'

services:
  mongodb:
    image: mongo:4.4.2
    restart: always
    container_name: local-mongodb
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGODB_ROOT_USERNAME}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_ROOT_PASSWORD}
    ports:
      - ${MONGODB_PORT}:27017
    volumes:
      - mongodb_database:/data/db
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js

volumes:
  mongodb_data:

mongo-init.js

require('dotenv').config()

print('mongo init start --------------------');

const pms = db.getSiblingDB(process.env.MONGODB_DATABASE)

pms.createUser({
  user: process.env.MONGODB_USERNAME,
  pwd: process.env.MONGODB_PASSWORD,
  roles: [
    {
      role: 'readWrite',
      db: process.env.MONGODB_DATABASE,
    },
  ],
});

print('mongo init end --------------------');

.环境

MONGODB_ROOT_USERNAME=root
MONGODB_ROOT_PASSWORD=password
MONGODB_DATABASE=product
MONGODB_USERNAME=user
MONGODB_PASSWORD=password
MONGODB_PORT=27017
70gysomp

70gysomp1#

我相信以优雅的方式实现您想要的最好方法是使用direnv

溶液

建议的解决方案使用以下文件:

  • Dotenv文件.env
  • 方向文件.envrc
  • Docker合成文件docker-compose.yml
  • 创建Mongo初始化脚本create_mongo_init.sh
  • 启动脚本up.sh

方向
首先,确保您安装了direnv

Dock-合成文件

编辑docker-compose.yml文件并确保其如下所示:

version: '3.7'

services:
    mongo:
        image: mongo:latest
        restart: always
        environment:
            MONGO_INITDB_ROOT_USERNAME: ${DB_USERNAME}
            MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD}
            MONGO_INITDB_DATABASE: ${DB_NAME}
        ports:
            - '27017-27019:27017-27019'
        volumes:
            - mongodb_database:/data/db
            - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro

.env文件创建

创建.env文件并输入:

DB_USERNAME=username
DB_PASSWORD=password
DB_NAME=db_name

.envrc文件创建

输入您的终端:

echo dotenv > .envrc

您应看到如下输出:

direnv: error .envrc is blocked. Run `direnv allow` to approve its content.

加载环境变量

因此,在终端中键入:

direnv allow .

如果您的Direnv安装正常,它将加载变量并输出以下内容:

direnv: loading .envrc                                                                               
direnv: export +DB_NAME +DB_PASSWORD +DB_USERNAME

Mongo初始化脚本

使用以下命令创建名为create_mongo_init.sh的文件:

#!/bin/sh

echo "\
print('mongo init start --------------------'); \n\
\n\
db.createUser( \n\
    { \n\
        user: \"$DB_USERNAME\", \n\
        pwd: \"$DB_PASSWORD\", \n\
        roles: [ \n\
            { \n\
                role: \"readWrite\", \n\
                db: \"$DB_NAME\" \n\
            } \n\
        ] \n\
    } \n\
) \n\
\n\
print('mongo init end ----------------------'); \n\
" > mongo-init.js

启动脚本

创建一个名为up.sh的文件,其内容如下:

#!/bin/sh

./create_mongo_init.sh
docker-compose up -d
rm mongo-init.js # Delete initialization script to avoid credentials leakage.

然后输入以下命令运行它:

. ./up.sh
deyfvvtc

deyfvvtc2#

这会帮到某人的!
Docker-compose.yml

version: "3.3"
services:
  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: myuser
      MONGO_INITDB_ROOT_PASSWORD: mypass
      MONGO_URI: ${MONGO_URI}
      MONGO_USER: ${MONGO_USER}
      MONGO_PWD: ${MONGO_PWD}
      MONGO_DB_NAME: ${MONGO_DB_NAME}
      MONGO_URI_TEST: ${MONGO_URI_TEST}
      MONGO_USER_TEST: ${MONGO_USER_TEST}
      MONGO_PWD_TEST: ${MONGO_PWD_TEST}
      MONGO_DB_NAME_TEST: ${MONGO_DB_NAME_TEST}
      MONGO_URI_DOCKER: ${MONGO_URI_DOCKER}
      MONGO_USER_DOCKER: ${MONGO_USER_DOCKER}
      MONGO_PWD_DOCKER: ${MONGO_PWD_DOCKER}
      MONGO_DB_NAME_DOCKER: ${MONGO_DB_NAME_DOCKER}
    volumes:
      - ./volume/mongo-data:/data/db
      - ./mongo-init:/docker-entrypoint-initdb.d/:ro

mongo-entrypoint.sh

echo '################ MONGO ENTRYPOINT START ################';

mongo -- "$MONGO_INITDB_DATABASE" <<EOF
db = db.getSiblingDB('$MONGO_DB_NAME_DOCKER');
db.createUser(
  {
    user: '$MONGO_USER_DOCKER',
    pwd: '$MONGO_PWD_DOCKER',
    roles: [{ role: 'readWrite', db: '$MONGO_DB_NAME_DOCKER' }],
  },
);
db.createCollection('users');

db = db.getSiblingDB('$MONGO_DB_NAME');
db.createUser(
  {
    user: '$MONGO_USER',
    pwd: '$MONGO_PWD',
    roles: [{ role: 'readWrite', db: '$MONGO_DB_NAME' }],
  },
);
db.createCollection('users');

db = db.getSiblingDB('$MONGO_DB_NAME_TEST');
db.createUser(
  {
    user: '$MONGO_USER_TEST',
    pwd: '$MONGO_PWD_TEST',
    roles: [{ role: 'readWrite', db: '$MONGO_DB_NAME_TEST' },{ role: 'dbAdmin', db: '$MONGO_DB_NAME_TEST' }],
  },
);
db.createCollection('users');
EOF

echo '################ MONGO ENTRYPOINT END ################';

.环境

MONGO_URI="mongodb://localhost:27017/vinsys_db_dev"
MONGO_USER='fancyuser'
MONGO_PWD='fancypass'
MONGO_DB_NAME='vinsys_db_dev'

MONGO_URI_TEST="mongodb://localhost:27017/vinsys_db_test"
MONGO_USER_TEST='fancyuser'
MONGO_PWD_TEST='fancypass'
MONGO_DB_NAME_TEST='vinsys_db_test'

MONGO_URI_DOCKER="mongodb://mongo:27017/vinsys_db_prod"
MONGO_USER_DOCKER='fancyuser'
MONGO_PWD_DOCKER='fancypass'
MONGO_DB_NAME_DOCKER='vinsys_db_prod'
mitkmikd

mitkmikd3#

以下代码在mongo中工作:6.0.4 docker图像。
mongo-init.js

db.auth(process.env["MONGO_INITDB_ROOT_USERNAME"], process.env["MONGO_INITDB_ROOT_PASSWORD"])

db = db.getSiblingDB(process.env["MONGO_INITDB_DATABASE"])

db.createUser({
  user: process.env["MONGODB_USERNAME"],
  pwd: process.env["MONGODB_PASSWORD"],
  roles: [
    {
      role: 'readWrite',
      db: process.env["MONGODB_DATABASE"],
    },
  ],
});

.env文件

MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=1qaz2WSX
MONGO_INITDB_DATABASE=admin
MONGODB_USERNAME=user
MONGODB_PASSWORD=password
MONGODB_DATABASE=rr-platform

docker-compose.yml

version: '3.8'

services:
  mongodb:
    image: mongo:6.0.4
    restart: unless-stopped
    env_file: .env
    ports:
      - '27017:27017'
    volumes:
      - ./.data/mongo:/data/db
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro

相关问题