Search code examples
python-3.xdockerenvironment-variablesubuntu-server

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


Solution

  • 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