在Docker容器中找不到环境变量

时间:2019-02-01 20:06:06

标签: python-3.x docker environment-variables ubuntu-server

我正在尝试在Ubuntu服务器上为不和谐的bot设置docker容器。

我已在Ubuntu服务器上运行以下命令:

export DISCORD_TOKEN = "*****"

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

在机器人代码中,我有:

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

运行容器时,它会给出python错误“ KeyError:'DISCORD_TOKEN'”

3 个答案:

答案 0 :(得分:0)

原始问题的答案(根据我上面的评论):

尝试将docker添加到当前用户的用户组。此后,登录到新的bash会话,再次设置环境变量:DISCORD_TOKEN(和任何其他变量),并运行不带f = open("file.txt","r") lines = list(f) #create a list of strings f.close() #don't forget to close our files when we're done. It's good practice. modified_lines = [] #empty list to put our modified lines in (extracted number, original line) for line in lines: #iterate over each line if line.strip(): #if there's anything there after we strip away whitespace score = line.split(' ')[2] #split our text on every space and take the third item score = int(score) #convert the string of our score into a number modified_lines.append([score, line]) #add our modified line to modified_lines #sort our list that now has the thing we want to sort based on is first sorted_modified_lines = sorted(modified_lines) #take only the string (not the number we added before) and print it without the trailing newline. for line in sorted_modified_lines: print(line[1].strip()) 的命令,如下所示:

sudo

那应该可以解决您的问题。

原因

之所以会发生这种情况,是因为当您使用sudo docker run --env DISCORD_TOKEN me/my-docker-repo 前缀启动容器时,它不在当前用户中,而是在root用户的环境变量定义中。因此,如果没有sudo前缀,它将在当前用户的环境变量定义中查找。


sudo的加载失败有关的另一个问题可能会有所帮助: Docker can’t load config file, but container works fine

答案 1 :(得分:0)

sudo默认情况下将Shell环境变量重置为最少的一组“已知安全”变量。如果您使用sudo -E选项,它将保留环境变量

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

您还可以直接在命令行上传递容器端环境变量,而无需在父shell中将其设置为这样

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

答案 2 :(得分:-1)

尝试一下

abcx

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

如果您想在python中设置env,请尝试此操作

TOKEN = os.getenv('DISCORD_TOKEN')