4

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'"

KGB33
  • 55
  • 2
  • 8

2 Answers2

2

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

Divij Sehgal
  • 647
  • 2
  • 11
  • 26
1

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
David Maze
  • 130,717
  • 29
  • 175
  • 215