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.txtCMD [ "python", "test.py" ]
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
ARG test
ENV test=$test
3) Run 'docker tag (image id) registry.heroku.com/(your app)/worker'
4) Run 'docker push registry.heroku.com/(your app)/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.
'heroku logs -a (app name)' OR 'heroku local'
Sample project: https://github.com/Cawleeflower/tutorial-buildarg.git


Comments
Post a Comment