Containerize your Conda environment

3 phases to containerize a conda/mamba environment for ease of use

Sami Islam

--

Containerize your conda environment
unDraw by Katerina Limpitsouni

Recently I read somewhere (most likely in medium) that it is becoming increasingly important to containerize a conda environment for ease of use. Since I have recently done something equivalent, why not post it here?

I am going to show how to containerize a mamba which according to them is “a fast drop-in alternative to conda”. The setup that I use is as follows:

  • Windows 10
  • Docker Desktop for Windows v4.24.0
  • Visual Studio Code to put together the docker files

Phase 1: Basic setup to containerize a conda environment

The Dockerfile to setup a conda environment based on your own settings is as follows:

FROM condaforge/mambaforge:23.3.1-0

RUN apt-get update \
&& apt-get install -y curl vim-tiny

ADD env .

EXPOSE 8888

# Setup mamba environment
RUN chmod 755 setup.sh \
&& /bin/sh -c "./setup.sh"

WORKDIR /

CMD tail -f /dev/null

It uses the mambaforge image as the base image. It copies the 3 files described below from the env folder into the root folder inside the container. It exposes port 8888 which is where the JupyterLab environment is going to be accessed. The setup.sh file is then executed to setup the actual mamba environment.

The 3 files copied are the following:

#!/usr/bin/bash

mamba env create -f myenv.yml
mamba init

The setup.sh file above creates a mamba environment using our own environment description in the myenv.yml file as follows:

name: myenv
channels:
- conda-forge
dependencies:
- matplotlib
- numpy
- pandas
- scikit-learn
- seaborn
- plotly
- ipython
- ipykernel
- cython
- jupyterlab
- scipy
- ipympl

This is where we can include all the package dependencies that we want to set up our Conda environment with.

To build the docker image we run the following:

docker build -t my-lab .

The build output on my environment running Docker Desktop for Windows looks like the…

--

--