Home > Blockchain >  Docker Swarm pass environment variable to container
Docker Swarm pass environment variable to container

Time:12-14

I have docker cloud yml file for deploying to different environment like testing, production,QA . I want to pass env variables to the container .this variable are available in my shell .I how can add environment property to my yml to pass it to container so i can use in react app. I am able to set healthcheck ,image value from shell Like for example MAX_LOG_SIZE is automatically picked from shell so is SERVICE_NAME so on(all capitilized string in this file) .but cannot pass to env varaible to containers . Like deploy_stage = MY_ENV_VARIABLE. BTW all shell vaibles are populated through azure devops pipeline library

version: "3.9"

services:
  SERVICE_NAME:
    deploy:
      mode: replicated
      placement:
        constraints: [ node.role == worker ]
        max_replicas_per_node: 1
      replicas: REPLICA_COUNT
      update_config:
        delay: 15s
        failure_action: rollback
        monitor: 60s
        order: stop-first
        parallelism: 1
    healthcheck:
      test: [ "CMD", "wget", "--spider", "HEALTH_CHECK_URL" ]
      interval: 60s
      timeout: 10s
      retries: 3
      start_period: 15s
    image: "CONTAINER_REGISTRY/DOCKER_IMAGE"     
    logging:
      driver: "json-file"
      options:
        max-size: "MAX_LOG_SIZE"
        max-file: "MAX_LOG_FILES"


CodePudding user response:

You can list your environment variables in the environment section like as follows:

version: "3.9"

services:
  SERVICE_NAME:
    deploy:
      mode: replicated
      placement:
        constraints: [ node.role == worker ]
        max_replicas_per_node: 1
      replicas: REPLICA_COUNT
      update_config:
        delay: 15s
        failure_action: rollback
        monitor: 60s
        order: stop-first
        parallelism: 1
    environment:
      # ENVIRONMET_VARIABLE_NAME: "environment variable value" 
      MAX_LOG_SIZE : your value
    healthcheck:
      test: [ "CMD", "wget", "--spider", "HEALTH_CHECK_URL" ]
      interval: 60s
      timeout: 10s
      retries: 3
      start_period: 15s
    image: "CONTAINER_REGISTRY/DOCKER_IMAGE"     
    logging:
      driver: "json-file"
      options:
        max-size: "MAX_LOG_SIZE"
        max-file: "MAX_LOG_FILES"

CodePudding user response:

If the var is set in your current shell, you can use env var with null (or empty) value.

services:
  foo:
    environment:
      SOMEVAR: null

If you want to have a default I would suggest doing it this way.

services:
  foo:
    environment:
      SOMEVAR: ${SOMEVAR:-mydefault}

In compose, those will additionally get picked up from an .env file, where shell takes precedence. I am not 100% sure if .env would also work with swarm.

  • Related