dockerdockerfileconda

Activating a conda environment when docker container launches


I have a java app, and it uses conda packages for some tasks. So my need is to activate a conda env when docker container starts. I have tried following in my docker file:

ENTRYPOINT ["/bin/bash", "-c", "source /opt/conda/bin/activate myenv && java -jar app.jar"]
ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "myenv", "java", "-jar", "app.jar"]

But none of these work, and I have to manually activate the env inside container.

What is correct way of doing it in Dockerfile?


Solution

  • Have you tried using adding the source command to activate Conda environment in the .bashrc file (or other rc config of other shells) using RUN and appending the PATH variable with path to environment bin /opt/conda/envs/myenv/bin and run the java command in ENTRYPOINT

    RUN echo "source /opt/conda/bin/activate myenv" > ~/.bashrc
    ENV PATH /opt/conda/envs/myenv/bin:$PATH
    ENTRYPOINT ["java", "-jar", "app.jar"]
    

    If the ENTRYPOINT didn't work, you could try using the original ENTRYPOINT command instead

    RUN echo "source /opt/conda/bin/activate myenv" > ~/.bashrc
    ENV PATH /opt/conda/envs/myenv/bin:$PATH
    ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "myenv", "java", "-jar", "app.jar"]
    

    Edit: per @DavidMaze's suggestion, I think you can also remove RUN command in the Dockerfile to avoid redundancy as .bashrc is only sourced when container shell is in interactive mode

    ENV PATH /opt/conda/envs/myenv/bin:$PATH
    ENTRYPOINT ["java", "-jar", "app.jar"]