Andrey
Andrey

Reputation: 663

how use docker-compose env file variables in different containers with golang?

.
├── articaleServer
│   ├── Dockerfile
│   ├── main.go
│   └── sources.json
├── butler
│   ├── Dockerfile
│   ├── main.py
│   └── requirements.txt
├── docker-compose.yml
├── frontEnd
│   ├── Dockerfile
│   ├── main.go
│   ├── tags.json
│   └── templates
│       ├── auth.html
│       ├── feed.html
│       ├── footer.html
│       ├── header.html
│       ├── main.html
│       └── today.html
└── server
    ├── Dockerfile
    ├── keys
    │   ├── app.rsa
    │   └── app.rsa.pub
    └── main.go

.env

MONGO_USERNSME=user
MONGO_USERNSME=password

I have .env file in path with docker-compose.yml and I need to use variables form it in other containers(articaleServer, butler, server) in go files like

mongoDBDialInfo := &mgo.DialInfo{
        Addrs:    []string{"mongodb://mongo:27017"},
        Username: os.Getenv("MONGO_USERNSME"),
        Password:  os.Getenv("MONGO_PASSWORD"),
    }

But go does't see it and pass nil

Upvotes: 1

Views: 4222

Answers (1)

lee-pai-long
lee-pai-long

Reputation: 2282

The .env file placed in the same directory as the docker-compose.yml is used for variable substitutions in the compose files only.

On the other hand, you can define a env_file key to pass env vars from a file to the container at runtime:

services: 
  some_service: 
    image: someimg
      env_file:
        - .env

It works like the environment statement in a Dockerfile or docker run -e.

As the list type implied you can use multiple files for example to override some generic config key for a specific service.

Upvotes: 3

Related Questions