6

I'm creating a docker image with, inside, a conda environment myEnv using a Dockerfile.

I would like, when running the docker image with

docker run -it myDockerImage

to get to a bash terminal with the environment already activated. I know we can pass variables and commands to docker run but I would like it to be done automatically.

I tried adding the following variants to the end of the Dockerfile but nothing seems to work:

CMD ["source /root/miniconda/bin/activate myEnv"]
CMD [".", "/root/miniconda/bin/activate", "myEnv"]
CMD ["source /root/miniconda/bin/activate myEnv; /bin/bash"]
Arseniy Banayev
  • 686
  • 9
  • 18
BiBi
  • 7,418
  • 5
  • 43
  • 69

1 Answers1

2

Do this with an ENTRYPOINT in your Dockerfile.

src/entrypoint.sh

#!/bin/bash

# enable conda for this shell
. /opt/conda/etc/profile.d/conda.sh

# activate the environment
conda activate my_environment

# exec the cmd/command in this process, making it pid 1
exec "$@"

src/Dockerfile

# ...
COPY ./entrypoint.sh ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
Arseniy Banayev
  • 686
  • 9
  • 18
  • 1
    This answer seems fine, but also consider this [simpler approach using `ENV PATH`](https://stackoverflow.com/a/57595180/) which doesn't require you have an `entryoint.sh` script. – Asclepius Feb 04 '20 at 12:52
  • @Acumenus setting the `PATH` variable might not be enough. According to the [conda documentation](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#activating-an-environment) it is not recommended because `conda activate` does more then just setting the `PATH`. – Peter Jan 20 '21 at 16:34
  • @Xochipilli Setting `PATH` has been sufficient for me for the past six months. I have had no real-world problem with it whatsoever. Everything essential works in the container. I wouldn't use or recommend this approach outside the container, however. – Asclepius Jan 20 '21 at 17:17