N P
N P

Reputation: 2619

Use environment variable from Dockerfile in Bash script

I have a really simple Redis bash script that loads some default values into Redis for when my application starts, run in a docker container.

I want to get an ENV var within the bash script passed into my Dockerfile, everytime I run the container and check the logs it says it can't find the set environment var.

My bash script is just

#!/usr/bin/env bash
redis-server --daemonize yes && sleep 1

if [ "$ENVIRONMENT_VAR" = "found" ]; then
    echo "found environment var"
fi

A snippet of my Dockerfile where I try and set a default for the value

ENV ENVIRONMENT_VAR notfound

CMD ["sh", "redis.sh"]

And my Docker-Compose I'm passing

environment:
  - ENVIRONMENT_VAR=found

Is there something special I need to do to use the ENV value in my bash script?

Upvotes: 3

Views: 3233

Answers (1)

Daviid
Daviid

Reputation: 238

What you are doing looks completely fine to me. I have implemented what you are trying to accomplish in case you missed something. First let's start with the Dockerfile :

From redis:alpine
WORKDIR /usr/app
ENV ENVIRONMENT_VAR notfound
COPY . .
CMD sh ./start.sh

Here I'm using a redis image to start with, declaring the environment variable, copy the script into the container and start it.

Second the docker-compose which also should be alike your implementation in somehow

version: '3.2'

services:
  redis:
    container_name: 'redis-test'
    build: .
    environment:
        - ENVIRONMENT_VAR=found
    restart: always

If you looked to the output using the docker-compose up command you will find the found environment var you trying to print

redis-test | 7:C 21 Apr 2020 10:30:14.247 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis-test | 7:C 21 Apr 2020 10:30:14.247 # Redis version=5.0.9, bits=64, commit=00000000, modified=0, pid=7, just started
redis-test | 7:C 21 Apr 2020 10:30:14.247 # Configuration loaded
redis-test | found environment var

you can debug this also by echo $ENVIRONMENT_VAR inside your container like what @David Maze mentioned

Upvotes: 3

Related Questions