简体   繁体   中英

Environment Variable cannot be found in docker container

I'm trying to setup a docker container on a Ubuntu server for a discord bot.

I have run the following on the Ubuntu server:

export DISCORD_TOKEN = "*****"

sudo docker run --env DISCORD_TOKEN  me/my-docker-repo

In the bot code I have:

import os
TOKEN = os.environ['DISCORD_TOKEN']

when the container is ran it gives the python error "KeyError: 'DISCORD_TOKEN'"

Answer to the original question(From my comment above):

Try adding docker to the current user's user group. Thereafter, login into a new bash session, set the environment variable: DISCORD_TOKEN(and any other variables) again and run the command without sudo as follows:

sudo docker run --env DISCORD_TOKEN  me/my-docker-repo

That should fix your problem.

Reason

This happens because when you start a container with the sudo prefix, it looks not in the current user, but in the root user's environment variable definitions. So without the sudo prefix, it looks in the current user's environment variable definitions.


The other problem regarding load failure of config file , this might help: Docker can't load config file, but container works fine

sudo by default resets the shell environment variables to a minimum set of "known safe" variables. If you use the sudo -E option it will preserve environment variables

sudo -E docker run --env DISCORD_TOKEN  me/my-docker-repo

You can also pass the container-side environment variables directly on the command line, without setting it as such in the parent shell

sudo docker run --env DISCORD_TOKEN="*****" me/my-docker-repo

Try this,

TOKEN = os.environ.get('DISCORD_TOKEN')

or,

TOKEN = os.getenv('DISCORD_TOKEN')

if you wanna set env in python try this,

os.environ["Key"] = Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM