Docker-compose env var无法正常工作

时间:2018-03-01 11:39:02

标签: docker docker-compose

我正在尝试在我的docker compose文件中设置env var,但var似乎没有传播到我的docker。

我的docker-compose:

test:
  build: ./
  environment:
    TESTVAR: "YOU ARE BEST"

我的dockerfile:

FROM alpine

RUN echo test variable is: $TESTVAR

输出:

Step 1/2 : FROM alpine
 ---> 3fd9065eaf02
Step 2/2 : RUN echo test variable is $TESTVAR
 ---> Running in d5f5505b26db
test variable is
Removing intermediate container d5f5505b26db
 ---> a9c019ac7eff
Successfully built a9c019ac7eff
Successfully tagged phpfpm_test:latest
Recreating phpfpm_test_1 ... done
Attaching to phpfpm_test_1

我错过了什么吗?

2 个答案:

答案 0 :(得分:3)

  

注意:如果您的服务指定了构建选项,则在构建期间,环境中定义的变量不会自动显示。使用build的args子选项来定义构建时环境变量。 - from docker docs

所以你可以使用参数(args)代替环境(environment):

Docker Compose(v2或v3)

// usings:
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.Configuration;

void ConsumeWebService()
{
    var myBinding = new CustomBinding("xxxxxAPIPortBinding");

    // Manually define Endpoint:
    //var myEndpoint = new EndpointAddress("http://localhost/myservice");

    // Or get from configuration file:
    ClientSection clientSection = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");
    ChannelEndpointElement myEndpoint = clientSection.Endpoints[0];

    // Define a communication channel, based on the interface, bindig e endpoint
    var myChannelFactory = new ChannelFactory<xxxxxAPI.PlunetAPI>(myBinding, myEndpoint.Address.AbsoluteUri);
    xxxxxAPI.PlunetAPIclient client = null;

    try
    {
        // Create the channel to consume the service
        client = myChannelFactory.CreateChannel();
        client.MyMethod();  //Calls some method
        ((ICommunicationObject)client).Close();
    }
    catch
    {
        if (client != null)
        {
            ((ICommunicationObject)client).Abort();
        }
    }
}

<强> Dockerfile

version: '2'  # or 3
services:
  test:
    build: 
      context: ./
    args:
      TESTVAR: 'YOU ARE BEST'

<强>要求:

  • Docker Compose :1.6.0+
  • Docker Engine :1.10.0 +

注意:您需要在FROM alpine ARG TESTVAR RUN echo "test variable is: $TESTVAR" 之后定义参数(ARG TESTVAR)以使用docker-compose文件(more info on StackOverflow)上指定的值。

答案 1 :(得分:-1)

您可以在docker-compose文件的同一目录中使用.env文件,对我有用