Docker 撰写:如何设置环境变量以在脚本中使用

Docker compose: How to set env variable to use in a script

我是 运行 webdriverIO (https://github.com/hulilabs/webdriverio) 测试通过 docker:

docker-compose run --rm webdriverio wdio

现在我需要用这个命令(ENV?)设置一个可以在测试文件中使用的变量。

describe('my awesome website', function () {
  it('should do some chai assertions', function () {
    browser.url(url) // <-- I need to set the variable (dev vs. prod)
    browser.getTitle().should.be.equal('Website title')
  })
})

我该怎么做?


配置

我的wdio.conf.js:

exports.config = {
  host: 'hub',
  port: 4444,
  specs: [
    './specs/**/*.js'
  ],
  capabilities: [
    { browserName: 'chrome' },
    { browserName: 'firefox' }
  ]
}

我的docker-compose.yml看起来像这样:

version: '2'
services:
    webdriverio:
        image: huli/webdriverio:latest
        depends_on:
            - chrome
            - firefox
            - hub
        environment:
            - HUB_PORT_4444_TCP_ADDR=hub
            - HUB_PORT_4444_TCP_PORT=4444
        volumes:
            - /app:/app

    hub:
        image: selenium/hub
        ports:
            - 4444:4444

    firefox:
        image: selenium/node-firefox
        ports:
            - 5900
        environment:
            - HUB_PORT_4444_TCP_ADDR=hub
            - HUB_PORT_4444_TCP_PORT=4444
        depends_on:
            - hub

    chrome:
        image: selenium/node-chrome
        ports:
            - 5900
        environment:
            - HUB_PORT_4444_TCP_ADDR=hub
            - HUB_PORT_4444_TCP_PORT=4444
        depends_on:
            - hub

首先你需要设置ENV变量为docker-compose.yml

services:
    webdriverio:
        image: huli/webdriverio:latest
        depends_on:
            - chrome
            - firefox
            - hub
        environment:
            - HUB_PORT_4444_TCP_ADDR=hub
            - HUB_PORT_4444_TCP_PORT=4444
            - APP_PROFILE=dev # <- here new variable
        volumes:
            - /app:/app

那么你需要在你的应用程序中读取这个变量

describe('my awesome website', function () {
  it('should do some chai assertions', function () {
    browser.url(process.env.APP_PROFILE)
    browser.getTitle().should.be.equal('Website title')
  })
})

此外,在您的 Dockerfile 中,您可以将 ENV 变量设置为默认值:

ENV APP_PROFILE=prod