I am a docker
novice, so apologies if this is a silly question.
As background, I am using a docker image that I have no ability to edit or change. I run the container with docker run [various-args] [image-name]
and the container is launched. If I subsequently run docker exec -it [ID] bash
, I can get a shell going from inside the container and it successfully executes a conda
environment needed for all my python code, so I can just run python script.py
and everything runs okay.
I wanted to automate this process for future use, so I wanted to put these commands into a single script so that I don't need to manually type or execute anything from within the environment. The solution I thought would work was this:
docker exec -it [ID] bash -c "python script.py"
but this doesn't work, giving an import error for the python code. My assumption is that the conda environment is not activated, so I try to execute conda activate my-env
, which kicks back a new error of:
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
So, I follow the instructions and run conda init bash
first to see if that helps, but this error still kicks back eventually. Ultimately, it seems like if I execute a bash shell first, then manually start running python code everything is fine, but if I try to do it all at once the conda environment cannot be set up for somme reason. Is there a way to make this work without editing the image itself, or is this something that would require rebuilding the image?
Thanks ins advance!
The conda activate
function is defined by code added to .bashrc
by the conda init
command. Bash will not source .bashrc
unless the -l
(--login
) flag is used.
However, rather than bothering with shell, Conda provides a conda run
command that executes within a specified environment. So, try something like
docker exec -it [ID] conda run -n my-env python script.py
For interactive scripts, one may also need some of the additional conda run
flags, such as --live-stream
or --no-capture-output
. See conda run -h
.