How to add environment variables into Heroku container

 Method 1: Using .env file 

NOTE: Please add your .env file into .gitignore to not make the file visiblein github.

Before we start, please make sure you have ran 'heroku scale worker=1 -a (app)' in your app. 

1) Create an .env file and add your environment variable like so:

your-environment-variable=123

2) In your code, import load_dotenv from dotenv like so:

import os
from dotenv import load_dotenv
load_dotenv()
test-env = os.getenv('your-environment-variable') 
print(test-env) 

Note: Please make sure you have requirements.txt present by doing 'pip freeze > requirements.txt'

3) Create your dockerfile

FROM python:latest
WORKDIR /
COPY . .
RUN pip install -r requirements.txt
CMD [ "python", "test.py" ]

4) Run 'heroku container:push worker -a (app name)'

5) Run 'heroku container:release worker -a (app name)'

6) Wait for 10-20 seconds...

7) You can test if your app is working by running 'heroku logs -a (app name)' or 'heroku logs'

Expected output:


Note: Please make sure to run 'heroku scale worker=1', or else heroku won't know where to run your code. 

Sample project: https://github.com/Cawleeflower/tutorial-env.git


Method 2: Add existing image in docker and push it to heroku

First, build your image locally. You can pass build arguments to the dockerfile and then set the build environment variables to the runtime environment variables.

1) Set the build arguments to the runtime environment variables in your dockerfile:
ARG test
ENV test=$test

2) Build image: 'docker build --build-arg test=123 -t sample-image .'

3) Run 'docker tag (image id) registry.heroku.com/(your app)/worker'

4) Run 'docker push registry.heroku.com/(your app)/worker'

5) Run 'heroku container:release worker -a registry.heroku.com/testenv2/worker'
Note: You need to run this command before running 'heroku scale worker=1 -a (app)', because heroku wouldn't be able to find process type (worker), so you need to release the process type (worker) before you can set where the worker should be ran.

6) You can test it by running:
'heroku logs -a (app name)' OR 'heroku local'

Note: If your app doesn't run, please do 'heroku scale worker=1 -a (app)'

Expected output:


Sample project: https://github.com/Cawleeflower/tutorial-buildarg.git



Comments

Popular posts from this blog

Support for the experimental syntax 'decorators' isn't currently enabled (5:3):

Running CQL scripts in Cassandra