Containers: Difference between revisions

From ACCRE Wiki

No edit summary
 
(43 intermediate revisions by 3 users not shown)
Line 1: Line 1:
==Containers==
Containers provide lightweight, virtualized operating environments that allow you to run an application and its dependencies in resource-isolated processes. They enable developers to package an application with all its dependencies into a standardized unit for software development. Unlike traditional virtual machines (VMs) that virtualize the entire hardware stack, containers virtualize at the OS level, with multiple containers running directly on top of the OS kernel. This makes them more portable, efficient, and scalable than VMs.


Containers are a form of lightweight, virtualized operating environments that allow you to run an application and its dependencies in resource-isolated processes. Containers enable developers to package an application with all of its dependencies into a standardized unit for software development.
== Apptainer/Singularity ==


Unlike traditional virtual machines (VMs) which virtualize the entire hardware stack, containers virtualize at the OS level, with multiple containers running atop the OS kernel directly. This means they are more portable, efficient, and scalable than VMs.
[https://apptainer.org/ Apptainer] (previously known as Singularity) is a tool that allows containers to run within a shared high-performance computing environment. This empowers users to control the OS environment (including software libraries) in which their jobs execute. For instance, a user can run within an Ubuntu 16.04 environment even if the underlying OS on the ACCRE cluster is a different Linux distribution (e.g., Rocky Linux). Docker containers, for security reasons, cannot be directly run in shared environments like the ACCRE cluster. However, Docker container images can be easily used as Apptainer container images, which are safe for cluster execution.


==Docker==


===Writing a Dockerfile===
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Here's an example of a Dockerfile:


1. Use an official Python runtime as a parent image
<blockquote style="border-left: 4px solid #ccc; padding-left: 10px;">
FROM python:3.7-slim
'''Note:''' The terms "Singularity" and "Apptainer" are used interchangeably in this document.
 
</blockquote>
2. Set the working directory in the container
WORKDIR /usr/src/app
 
3. Copy the current directory contents into the container at /usr/src/app
COPY . .
 
4. Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
 
5. Make port 80 available to the world outside this container
EXPOSE 80
 
6. Define environment variable
ENV NAME World
 
7. Run app.py when the container launches
CMD ["python", "app.py"]


Detailed information on Dockerfile instructions can be found at the [https://docs.docker.com/engine/reference/builder/ Dockerfile reference].


===Creating a Container Using Docker===
When running within an Apptainer container, a user retains the same permissions and privileges they would have outside the container. An Apptainer image typically needs to be developed and built on a Linux machine where you have administrative access (e.g., a personal machine). If you lack administrative access to a Linux machine, you can create a virtual Linux machine using free tools like [https://www.vagrantup.com/ Vagrant] or [https://www.virtualbox.org/ VirtualBox]. Apptainer offers helpful documentation on this process [https://apptainer.org/docs/user/latest/].
To create a Docker container, you first need to build an image from your Dockerfile, and then run a container from this image:


docker build -t my-python-app .
A user's cluster storage is accessible from within the Apptainer container, but operations requiring root/sudo privileges (such as installing system software) are not permitted within the container's context when run on the cluster. Below are basic instructions for running Apptainer on the cluster. It is highly recommended to explore the comprehensive Apptainer documentation. Please also refer to the [https://www.youtube.com/watch?v=Hj5eTZGUsDM apptainer deep dive video] provided by the CIQ.
docker run -p 4000:80 my-python-app


These commands build and run your application in a Docker container.
=== Building an Apptainer Image ===


===Creating a Docker Hub Account and Uploading the Container to Docker Hub===
Once you have [https://apptainer.org/user-docs/master/ installed Apptainer on your own Linux machine or virtual machine], you are ready to create your image. First, create a spec file named Apptainer with the following content:
To share your Docker container images, you need to upload them to Docker Hub. First, [https://hub.docker.com/signup create a Docker Hub account]. Then follow these steps:


1. Authenticate your Docker client to Docker Hub:
<pre>
  docker login
BootStrap: docker
From: ubuntu:16.04
2. Tag your image to match your Docker Hub username:
  docker tag my-python-app username/my-python-app
3. Upload your image to Docker Hub:
  docker push username/my-python-app


Complete instructions can be found [https://docs.docker.com/docker-hub/ here].
%runscript
echo "This is what happens when you run the container..."


==Docker Compose==
%post
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
apt-get update
apt-get -y install python3 python3-numpy python3-scipy
# install any other software you need here...
mkdir /nobackup /data /panfs
</pre>


Here's an example `docker-compose.yml` file for the application above:
In this file:


version: '3'
* <code>BootStrap: docker</code> and <code>From: ubuntu:16.04</code> instruct Singularity to build an image based on the latest version of Ubuntu 16.04, pulling the base image from Docker Hub.
services:
* The <code>%runscript</code> section defines commands or tasks that will execute each time a container of this image is run.
  web:
* The <code>%post</code> section contains one-time setup steps to be performed inside the image. Here, <code>apt-get</code> is used to install Python 3 with NumPy and SciPy. You can add commands to install any other necessary software.
    build: .
* Creating the directories <code>/nobackup</code>, <code>/data</code>, and <code>/panfs</code> within the <code>%post</code> section is crucial for accessing your cluster storage from within the container. Failure to do so will result in a warning message when running the container on the cluster. Specifically, creating <code>/panfs</code> ensures access to your entire <code>/home</code> space from within the container.
    ports:
    - "4000:80"
With this file in place, you run the following command to start your application:


docker-compose up
To build the image, execute the following command on your Linux machine with administrative privileges:


And to stop your application, you would use:
<pre>
docker-compose down
# on your personal Linux machine
sudo apptainer build ubuntu16-accre.sif Apptainer
</pre>


More information on Docker Compose can be found [https://docs.docker.com/compose/ here]
===Running Containers hosted in Docker Hub or Singularity Hub ===


==Using Docker Containers in ACCRE With Singularity==
Often, creating your own image is unnecessary as others may have already created suitable ones. [https://hub.docker.com/ Docker Hub] and [https://cloud.sylabs.io/library Sylabs Cloud] host registries of images contributed by various users. The example below, in fact, pulls its base image from Docker Hub. If you find an image you wish to use directly, you can either build it locally or run it directly.


ACCRE users can run their Docker containers using Singularity, which is a container platform focused on supporting "mobility of compute" — the ability to move compute environments and maintain reproducibility.
Building the image locally is advisable if you plan to run it multiple times, as it avoids repeated downloads from the web, which can be slow. You can use the <code>singularity pull</code> subcommand to pull a container from the cloud and create a runnable container image. Since pull command does not rely on having a sudo access, you can run pull command directly on ACCRE.


Since Singularity can import Docker images directly from Docker Hub, you can work on your local machine within a Docker container and then easily transfer and run it within ACCRE's infrastructure.
<pre>
# From the cluster
apptainer pull ubuntu16-accre.sif docker://library/ubuntu:16.04
</pre>


Here is how you would pull and run a Docker container inside ACCRE using Singularity:
If you need to modify the container (e.g., adding access to ACCRE storage), it's recommended to create a spec file as described earlier.


1. First, load Singularity module [Generally, this is only required if instruction 2 doesn't work]:
=== Running an Apptainer Image on the Cluster ===
    ml GCC Singularity
<blockquote style="border-left: 4px solid #ccc; padding-left: 10px;">
2. Then pull the Docker image from Docker Hub:
'''Note:''' You must explicitly set bind mount to make any directory available inside of the container. See [[#Mounting Directories|Mounting Directories.]]
    singularity pull docker://username/my-python-app
</blockquote>
3. Finally, run the container:
    singularity exec my-python-app.sif python app.py
This enables easy and seamless transitioning from development to production in HPC environments like ACCRE.


Remember to comply with ACCRE's guidelines when using Singularity, and to utilize the compute resources responsibly.
Once your image is successfully created, you can run the container using Apptainer commands. Apptainer is one of our core software and doesn’t have to be loaded through module load command. You can access the container’s shell using the following command on the cluster:


== Apptainer/Singularity ==
<pre>
# From the cluster
apptainer shell ubuntu16-accre.sif
</pre>


[https://apptainer.org/ Apptainer(previously known as Singularity)] is a tool that allows containers to be run within a shared high-performance computing environment. This enables users to control the OS environment (including software libraries) that their jobs run within. For example, if a user wishes to run within an Ubuntu 16.04 environment he or she may do so despite the fact that the OS on the ACCRE cluster is a completely different Linux distribution (i.e. CentOS)! Docker containers themselves cannot be run in a shared environment like the ACCRE cluster for security reasons. However, Docker container images can easily be run as Singularity container images, which are safe to run on the cluster.
The <code>shell</code> subcommand is useful for interactive work. Note that any new data created inside the container will persist outside its context. For batch processing (e.g., within a SLURM job), use the <code>exec</code> subcommand instead. For example:


  [Note: The terms singularity and apptainer are used interchangeably in this document.]
<pre>
apptainer exec ubuntu16-accre.sif /path/to/my/script.sh
</pre>


When running within a Singularity container, a user has the same permissions and privileges that he or she would have outside the container. A Singularity image generally must first be developed and built from a Linux machine where you have administrative access (i.e. a personal machine), although ACCRE makes standard images available to all cluster users at <code>/scratch/singularity-images</code> . If you do not have administrative access to a Linux machine, you can create a virtual Linux machine using a free tool like [https://www.vagrantup.com/ Vagrant] or [https://www.virtualbox.org/ VirtualBox]. Singularity has some helpful documentation for how to do this [https://docs.sylabs.io/guides/latest/user-guide/ here] .
Here, <code>script.sh</code> contains the processing steps you want to execute within the batch job. You can also pass a generic Linux command to the <code>exec</code> subcommand. Pipes and redirected output are supported with <code>exec</code>. The following demonstrates the change in Linux distribution when entering a Apptainer container:


A user’s cluster storage may be accessed from within the Singularity container, but no operations (e.g. the installation of system software) that require root/sudo privileges are allowed within the context of the Singularity container when run from the cluster. Below are some basic instructions for running Singularity on the cluster. The Singularity documentation is very helpful, so we suggest you invest some time reading through it as well.
<pre>
[jill@vmps10 ~]$ cat /etc/*release
CentOS release 6.9 (Final)
...
[jill@vmps10 ~]$ apptainer shell ubuntu16-accre.sif
Apptainer> cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
...
Apptainer ubuntu-16.04.simg:~> exit
exit
</pre>


ACCRE also hosted a seminar on Singularity in Summer 2017. [https://www.vanderbilt.edu/accre/singularity/ The recording can be found here.] Some of the information in this presentation is out of date as new features have been added to Singularity since this recording, but the same principles apply. Please also refer to the [https://www.youtube.com/watch?v=UbxCwcreJqU | basic singularity commands video] provided by the singularity team.
=== Mounting Directories ===
In our old CentOS7 environment, certain commonly used paths such as /data, /panfs, and /home were automatically bind-mounted into Apptainer containers by default. However, in the R9 environment, this automatic bind-mounting setup is not configured by default. The rationale behind this decision is to minimize unintended side effects when users run containers. You must manually specify bind mounts to access files and directories on the host system from within the container. This can be done using either the <code>APPTAINER_BINDPATH</code> environment variable or the <code>--bind/-B</code>flag when invoking the container.
Using the <code>APPTAINER_BINDPATH</code> Environment Variable :
<pre>
export APPTAINER_BINDPATH="/panfs,/data,/nobackup"
apptainer shell my_python_container.sif
</pre>
Using the <code>--bind/-B</code> Flag.  
<pre>
apptainer shell --bind=/panfs:/panfs,/data:/data python_container.sif
</pre>
If the destination path inside the container is omitted <code>(e.g., --bind=/data)</code>, Apptainer will mount it to the same path inside the container.


=== Building a Singularity Image ===
=== Running GPU-Enabled Containers ===


Once you have [https://apptainer.org/user-docs/master/ installed Singularity on your own Linux machine or virtual machine] , you are ready to create your image. First, create a spec file called Singularity that looks like the following:
Apptainer supports running on GPUs from within containers. The <code>--nv</code> option must be passed to the <code>exec</code> or <code>shell</code> subcommand. Here's an example of a spec file for creating a GPU-enabled Tensorflow/Keras image for use on ACCRE:


<pre>BootStrap: docker
<pre>
From: ubuntu:16.04
BootStrap: docker
From: tensorflow/tensorflow:latest-gpu-py3


%runscript
%help
    echo &quot;This is what happens when you run the container...&quot;
Apptainer image with TensorFlow 1.7 and Keras running on python 3.5 with GPU support.


%post
%post
    apt-get update
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:$PATH
    apt-get -y install python3 python3-numpy python3-scipy
pip3 install -U keras
    # install any other software you need here...
mkdir /nobackup /data /panfs
    mkdir /scratch /data /gpfs22 /gpfs23</pre>
</pre>
 
Instantiating a container from such an image would look like this:
<pre>
$ apptainer exec --nv my-singularity-image.sif python -c "import tensorflow"
</pre>


In this file, we are telling Singularity we want to build an image based on the latest version of Ubuntu 16.04. The base image is pulled from Docker Hub (see below). The '''''%runscript''''' section is for defining commands or tasks that you want to run each time you run a container of this image. The '''''%post''''' section contains one-time setup steps that you want to be inside the image. This is where you install your custom software. In this case, we use <code>apt-get</code> to install Python 3 with NumPy and SciPy included. Finally, it’s important if you want to access all your cluster space from within the container to create the following directories from within the container: /scratch, /data, /gpfs22, and /gpfs23. If you don’t make these directories within the container (inside the '''''%post''''' section), you will get a warning message when you run a container of this image on the cluster. In particular, creating /gpfs22 will ensure you have access to all your /home space from within a container run on the cluster. To build the image, run the following command on your Linux machine where you have admin rights:
Alternatively, you can run a GPU-enabled image directly from Docker Hub. Here's an example SLURM script for running a GPU-enabled Tensorflow container on ACCRE GPUs:


<pre># on your personal Linux machine
<pre>
sudo singularity build ubuntu16-accre.simg Singularity</pre>
#!/bin/bash
#SBATCH --account=MY_GPU_ACCOUNT
#SBATCH --partition=pascal
#SBATCH --gres=gpu:1
#SBATCH --mem=10G
#SBATCH --time=12:00:00
 
# Clone tensorflow repo to run a tutorial
git clone https://github.com/tensorflow/models.git
apptainer exec --nv docker://tensorflow/tensorflow:latest-gpu \
python ./models/tutorials/image/mnist/convolutional.py
</pre>


=== Building Containers Directly from Docker Hub or Singularity Hub ===
Again, we recommend you to use <code>apptainer pull</code> to build an image locally from docker hub for repeated usage.


Often it is not necessary to create your own image because someone else has already created one for you! [https://hub.docker.com/ Docker Hub] and [https://singularity-hub.org/ Singularity Hub] contain registries of images that have been contributed by various users. In fact, the first example above pulls its base image from Docker Hub. If you have found an image that you would like to run directly, you have the option of building it locally or running it directly.
== Using Docker to build an image ==


Building the image locally is a good option if you intend to run it as a container multiple times. In this way you don’t need to re-download the image from the web repeatedly (which can be slow). Here is an example of how you might build a local version of an image from Docker Hub:
Since Apptainer supports running Docker images, many users prefer to build docker image locally on their computer, then either create an image archive to transfer to the cluster using tools like scp, or upload the image to Docker Hub so it can be pulled directly from the cluster.
If you have a container image already available in Docker Hub or any other repo hosting the Docker image, follow [[#Building Containers Directly from Docker Hub or Singularity Hub|this instruction]] on how to run docker container in Apptainer.


<pre>sudo singularity build ubuntu16-accre.simg docker://library/ubuntu:16.04</pre>
=== Writing a Dockerfile ===
Note you can also use the <code>singularity pull</code> subcommand to accomplish the same thing:


<pre>singularity pull docker://library/ubuntu:16.04</pre>
A Dockerfile is a text document containing all the commands a user would execute on the command line to assemble an image. Here's an example:
If you need to modify the container in any way (e.g. adding access to ACCRE storage), we recommend creating a spec file as shown above.


=== Running a Singularity Image on the Cluster ===
<pre>
# 1. Use an official Python runtime as a parent image
FROM python:3.7-slim


Once you have successfully created your image, you can shell into it with the following command:
# 2. Set the working directory in the container
WORKDIR /usr/src/app


<pre># From the cluster
# 3. Copy the current directory contents into the container at /usr/src/app
singularity shell ubuntu16-accre.simg</pre>
COPY . .
''Note: In the past users had to load Singularity using an Lmod command; as of the upgrade of the cluster to CentOS 7, this is no longer needed.''


The shell subcommand is useful for interactive work. Note that you can create new data inside the container that will persist outside the context of the container. For batch processing (e.g. within a SLURM job), you should use the ''exec'' subcommand instead. For example:
# 4. Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt


<pre>singularity exec ubuntu16-accre.simg /path/to/my/script.sh</pre>
# 5. Make port 80 available to the world outside this container
Where script.sh script contains the processing steps you want to run from within the batch job. You can also pass a generic Linux command to the ''exec'' subcommand. Pipes and redirected output are supported with the ''exec'' subcommand. Below is a quick demonstration showing the change in Linux distribution:
EXPOSE 80


<pre>[jill@vmps10 ~]$ cat /etc/*release
# 6. Define environment variable
CentOS release 6.9 (Final)
ENV NAME World
LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch
CentOS release 6.9 (Final)
CentOS release 6.9 (Final)


[jill@vmps10 ~]$ singularity shell ubuntu16-accre.img
# 7. Run app.py when the container launches
Singularity: Invoking an interactive shell within container...
CMD ["python", "app.py"]
Singularity ubuntu-16.04.simg:~&gt; cat /etc/*release
</pre>
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION=&quot;Ubuntu 16.04.4 LTS&quot;
NAME=&quot;Ubuntu&quot;
VERSION=&quot;16.04.4 LTS (Xenial Xerus)&quot;
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME=&quot;Ubuntu 16.04.4 LTS&quot;
VERSION_ID=&quot;16.04&quot;
HOME_URL=&quot;http://www.ubuntu.com/&quot;
SUPPORT_URL=&quot;http://help.ubuntu.com/&quot;
BUG_REPORT_URL=&quot;http://bugs.launchpad.net/ubuntu/&quot;
VERSION_CODENAME=xenial
UBUNTU_CODENAME=xenial
Singularity ubuntu-16.04.simg:~&gt; exit
exit
[jill@vmps10 ~]$</pre>


=== Running GPU-Enabled Containers ===
=== Creating and Running Docker Image ===


Singularity supports running on GPUs from within containers. The <code>--nv</code> option must be passed to the ''exec'' or ''shell'' subcommand. Here is an example of a spec file for generating a GPU-enabled Tensorflow/Keras image to be run on ACCRE:
You can use <code>docker build</code> command to create a Docker image from the Dockerfile. Pass the directory on which you have the Dockerfile as an argument to <code>docker build</code> command to build the image. <code>docker run</code> command allows us to run that image as a container in local machine and check if the container is working as intended.


<pre>BootStrap: docker
<pre>
From: tensorflow/tensorflow:latest-gpu-py3
# This creates a docker image named my-python-app using the Dockerfile from current directory
docker build -t my-python-app .
docker run -p 4000:80 my-python-app
</pre>


%help
Now that you have built a container image in your local machine, you can transfer that image to the cluster to be able to run it through Apptainer. Here are the two recommended process you could follow to do that :
    Singularity image with TensorFlow 1.7 and Keras running on python 3.5 with GPU support.  


%post
==== Option 1 : Creating a Docker Hub Account and Uploading the Image to Docker Hub ====
    export LC_ALL=C
    export PATH=/bin:/sbin:/usr/bin:/usr/sbin:$PATH
    pip3 install -U keras
    mkdir /scratch /data /panfs </pre>
The instantiation of a container from such an image would look like:


<pre>$ ml GCC Singularity
To create a sharable Docker container images, you can upload them to Docker Hub. [https://hub.docker.com/signup Create a Docker Hub account] and follow these steps:
$ singularity exec --nv my-singularity-image.simg python -c &quot;import tensorflow&quot;</pre>
Alternatively, you could run a GPU-enabled image directly from Docker Hub. Here is an example SLURM script for running a GPU-enabled Tensorflow container on ACCRE GPUs:


<pre>#!/bin/bash
Authenticate your Docker client to Docker Hub:
#SBATCH --account=MY_GPU_ACCOUNT
<pre>
#SBATCH --partition=pascal
docker login
#SBATCH --gres=gpu:1
</pre>
#SBATCH --mem=10G
#SBATCH --time=12:00:00


# Clone tensorflow repo to run a tutorial
Tag your image to match your Docker Hub username:
git clone https://github.com/tensorflow/models.git
<pre>
singularity exec --nv docker://tensorflow/tensorflow:latest-gpu \
docker tag my-python-app username/my-python-app
    python ./models/tutorials/image/mnist/convolutional.py</pre>
</pre>


==Commonly Encountered Errors==
Upload your image to Docker Hub:
<pre>
docker push username/my-python-app
</pre>
Upon successfully publishing the docker image in Docker hub, you can follow [[#Building Containers Directly from Docker Hub or Singularity Hub | this section ]] to run the docker container.


When working with containers and deploying applications, you may encounter a range of common errors. Below are a few typical issues and their probable solutions:
==== Option 2 : Saving Docker Image and Running it with Apptainer ====


===Missing Libraries===
If you prefer not to use Docker Hub, you can save your Docker image as an archive, transfer it to your cluster, and run it using Apptainer. Follow these steps:
'''Symptoms:''' Errors stating that a library or dependency is not found when attempting to run your application inside a container.


'''Possible Solutions:'''
Save your Docker image as a tar archive
* Ensure that all required libraries are listed in your `requirements.txt` (for Python) or an equivalent dependency file for your programming language.
<pre>
* Double-check the Dockerfile to ensure the `COPY` command is correctly copying the dependency file into the container and that the `RUN` command properly installs all dependencies.
docker save -o my-python-app.tar my-python-app
* Make sure that you are binding (the -B flag) the right paths when running the singularity container.
</pre>


  singularity run -B /accre,/cvmfs,/data/your_datapath:/workdir/data/ container.sif
Transfer the image archive to your cluster using scp
  # here the /workdir/data is the path that is used by services inside the container.
<pre>
scp my-python-app.tar user@cluster-address:/path/to/destination
</pre>


===Broken Links/Symlinks===
On the cluster, load and convert the Docker image using Apptainer
'''Symptoms:''' The application fails due to links pointing to files or directories that do not exist within the container's filesystem.
<pre>
apptainer build my-python-app.sif docker-archive://my-python-app.tar
</pre>


'''Possible Solutions:'''
Run the container using Apptainer
* Verify that the file or directory the link is pointing to exists within the container. You might need to adjust the Dockerfile to include the necessary files or directories using the `COPY` or `ADD` command.
<pre>
* For symlinks to paths outside the container (e.g., shared volumes), ensure that the corresponding volumes are correctly mapped and accessible when running the container with the `docker run -v` option.
apptainer run my-python-app.sif
</pre>


===Permission Issues===
== Commonly Encountered Errors ==
'''Symptoms:''' Errors relating to file or directory permissions, often indicating that the application does not have the necessary access rights.


'''Possible Solutions:'''
=== Missing Libraries ===
* Consider setting the appropriate permissions on files and directories using the `chmod` and `chown` commands within the Dockerfile.
* If running the container as a non-root user, ensure the user is correctly set up with the necessary permissions on the relevant files and directories.


===Environment Variables Not Set===
'''Symptoms:''' Errors indicating that a library or dependency is not found when trying to run your application inside a container.
'''Symptoms:''' Application behavior indicates that environment variables expected by the application are not set or have incorrect values.


'''Possible Solutions:'''
'''Possible Solutions:'''
* Use the `ENV` instruction in the Dockerfile or ```%environment``` section in your singularity definition file to set environment variables explicitly.
* Ensure all necessary libraries are listed in your <code>requirements.txt</code> (for Python) or the equivalent dependency file.
* When running the container, you can also set environment variables during runtime as well like so:  
* Double-check your Dockerfile to confirm the <code>COPY</code> command correctly transfers the dependency file and that the <code>RUN</code> command installs dependencies.
* Verify that you are correctly binding paths using the <code>-B</code> flag:
<pre>
apptainer run -B /accre,/cvmfs,/data/your_datapath:/workdir/data/ container.sif
</pre>


  env_var1=val1 env_var1=val2 singularity run -e "VARIABLE_NAME=value" my-image
=== Broken Links/Symlinks ===


===Multiple Environment Variables Overlapping ===
'''Symptoms:''' The application fails because links point to files or directories that do not exist within the container's filesystem.
If you have setup conda or pip installations in you profile folder, they get available in the container. This might conflict with the container setup which is unaware of programs installed in your home folder. To avoid such situations, you might need to run singularity with ```--cleanenv``` option i.e.  


singularity run -e ./lolcow.sif
'''Possible Solutions:'''
* Ensure that the path is mounted properly to the container.  
* Ensure that the paths you are mounting exist and are accessible on the host system
* Confirm that the file or directory the link points to exists within the container.


===Port Binding Conflicts===
=== Environment Variables Not Set ===
'''Symptoms:''' The container does not start, or the application is not accessible, with errors indicating that ports are already in use.
 
'''Symptoms:''' Application behavior suggests environment variables are missing or incorrect.


'''Possible Solutions:'''
'''Possible Solutions:'''
* Verify that the ports you are trying to expose and bind to the host machine are not already in use by running `netstat -tuln` on the host.
* Use the <code>ENV</code> instruction (Docker) or <code>%environment</code> section (Apptainer) to set variables.
* Change the port mappings in the Dockerfile's `EXPOSE` instruction or when using the `docker run -p` command to avoid conflicts.
* Set environment variables at runtime:
<pre>
env_var1=val1 env_var2=val2 apptainer run -e "VARIABLE_NAME=value" my-image
</pre>


===Image Not Found/Incorrect Tag===
=== Multiple Environment Variables Overlapping ===
'''Symptoms:''' Attempting to run or pull an image fails because the image cannot be found or the tag specified does not exist.


'''Possible Solutions:'''
If you have Conda or pip installations in your profile folder, they might interfere with the container’s setup.
* Verify that the image name and tag are spelled correctly.
* Ensure the image was successfully built and pushed to the registry (e.g., Docker Hub) if pulling from a remote source.
* When building locally, ensure you have used the correct tag with the `docker build -t` command.


Remember to regularly check the output during the image build process for warnings that may indicate potential problems. Moreover, consult the official Docker documentation and ACCRE's resources for in-depth troubleshooting guides and best practices.
'''Solution:'''
=== ACCRE Singularity GitHub Repository ===
<pre>
apptainer run --cleanenv ./lolcow.sif
</pre>


ACCRE has a [https://github.com/accre/singularity Singularity GitHub repository] if you would like to see more examples.
== ACCRE Apptainer GitHub Repository ==


We are constantly working on updating the content, but because of the ever changing nature of technology, some of the contents in our Github Repository are outdated. Hence, we also encourage users to contribute their own examples to the repo!
ACCRE maintains an [https://github.com/accre/singularity Apptainer GitHub repository] with more examples.
While we continuously work to update the content, due to the rapidly evolving nature of technology, some content in our GitHub Repository may be outdated. Therefore, we also encourage users to contribute their own examples to the repository!

Latest revision as of 19:04, 20 May 2026

Containers provide lightweight, virtualized operating environments that allow you to run an application and its dependencies in resource-isolated processes. They enable developers to package an application with all its dependencies into a standardized unit for software development. Unlike traditional virtual machines (VMs) that virtualize the entire hardware stack, containers virtualize at the OS level, with multiple containers running directly on top of the OS kernel. This makes them more portable, efficient, and scalable than VMs.

Apptainer/Singularity

Apptainer (previously known as Singularity) is a tool that allows containers to run within a shared high-performance computing environment. This empowers users to control the OS environment (including software libraries) in which their jobs execute. For instance, a user can run within an Ubuntu 16.04 environment even if the underlying OS on the ACCRE cluster is a different Linux distribution (e.g., Rocky Linux). Docker containers, for security reasons, cannot be directly run in shared environments like the ACCRE cluster. However, Docker container images can be easily used as Apptainer container images, which are safe for cluster execution.


Note: The terms "Singularity" and "Apptainer" are used interchangeably in this document.


When running within an Apptainer container, a user retains the same permissions and privileges they would have outside the container. An Apptainer image typically needs to be developed and built on a Linux machine where you have administrative access (e.g., a personal machine). If you lack administrative access to a Linux machine, you can create a virtual Linux machine using free tools like Vagrant or VirtualBox. Apptainer offers helpful documentation on this process [1].

A user's cluster storage is accessible from within the Apptainer container, but operations requiring root/sudo privileges (such as installing system software) are not permitted within the container's context when run on the cluster. Below are basic instructions for running Apptainer on the cluster. It is highly recommended to explore the comprehensive Apptainer documentation. Please also refer to the apptainer deep dive video provided by the CIQ.

Building an Apptainer Image

Once you have installed Apptainer on your own Linux machine or virtual machine, you are ready to create your image. First, create a spec file named Apptainer with the following content:

BootStrap: docker
From: ubuntu:16.04

%runscript
	echo "This is what happens when you run the container..."

%post
	apt-get update
	apt-get -y install python3 python3-numpy python3-scipy
	# install any other software you need here...
	mkdir /nobackup /data /panfs

In this file:

  • BootStrap: docker and From: ubuntu:16.04 instruct Singularity to build an image based on the latest version of Ubuntu 16.04, pulling the base image from Docker Hub.
  • The %runscript section defines commands or tasks that will execute each time a container of this image is run.
  • The %post section contains one-time setup steps to be performed inside the image. Here, apt-get is used to install Python 3 with NumPy and SciPy. You can add commands to install any other necessary software.
  • Creating the directories /nobackup, /data, and /panfs within the %post section is crucial for accessing your cluster storage from within the container. Failure to do so will result in a warning message when running the container on the cluster. Specifically, creating /panfs ensures access to your entire /home space from within the container.

To build the image, execute the following command on your Linux machine with administrative privileges:

# on your personal Linux machine
sudo apptainer build ubuntu16-accre.sif Apptainer

Running Containers hosted in Docker Hub or Singularity Hub

Often, creating your own image is unnecessary as others may have already created suitable ones. Docker Hub and Sylabs Cloud host registries of images contributed by various users. The example below, in fact, pulls its base image from Docker Hub. If you find an image you wish to use directly, you can either build it locally or run it directly.

Building the image locally is advisable if you plan to run it multiple times, as it avoids repeated downloads from the web, which can be slow. You can use the singularity pull subcommand to pull a container from the cloud and create a runnable container image. Since pull command does not rely on having a sudo access, you can run pull command directly on ACCRE.

# From the cluster
apptainer pull ubuntu16-accre.sif docker://library/ubuntu:16.04

If you need to modify the container (e.g., adding access to ACCRE storage), it's recommended to create a spec file as described earlier.

Running an Apptainer Image on the Cluster

Note: You must explicitly set bind mount to make any directory available inside of the container. See Mounting Directories.

Once your image is successfully created, you can run the container using Apptainer commands. Apptainer is one of our core software and doesn’t have to be loaded through module load command. You can access the container’s shell using the following command on the cluster:

# From the cluster
apptainer shell ubuntu16-accre.sif

The shell subcommand is useful for interactive work. Note that any new data created inside the container will persist outside its context. For batch processing (e.g., within a SLURM job), use the exec subcommand instead. For example:

apptainer exec ubuntu16-accre.sif /path/to/my/script.sh

Here, script.sh contains the processing steps you want to execute within the batch job. You can also pass a generic Linux command to the exec subcommand. Pipes and redirected output are supported with exec. The following demonstrates the change in Linux distribution when entering a Apptainer container:

[jill@vmps10 ~]$ cat /etc/*release
CentOS release 6.9 (Final)
...
[jill@vmps10 ~]$ apptainer shell ubuntu16-accre.sif
Apptainer> cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
...
Apptainer ubuntu-16.04.simg:~> exit
exit

Mounting Directories

In our old CentOS7 environment, certain commonly used paths such as /data, /panfs, and /home were automatically bind-mounted into Apptainer containers by default. However, in the R9 environment, this automatic bind-mounting setup is not configured by default. The rationale behind this decision is to minimize unintended side effects when users run containers. You must manually specify bind mounts to access files and directories on the host system from within the container. This can be done using either the APPTAINER_BINDPATH environment variable or the --bind/-Bflag when invoking the container. Using the APPTAINER_BINDPATH Environment Variable :

export APPTAINER_BINDPATH="/panfs,/data,/nobackup"
apptainer shell my_python_container.sif

Using the --bind/-B Flag.

apptainer shell --bind=/panfs:/panfs,/data:/data python_container.sif

If the destination path inside the container is omitted (e.g., --bind=/data), Apptainer will mount it to the same path inside the container.

Running GPU-Enabled Containers

Apptainer supports running on GPUs from within containers. The --nv option must be passed to the exec or shell subcommand. Here's an example of a spec file for creating a GPU-enabled Tensorflow/Keras image for use on ACCRE:

BootStrap: docker
From: tensorflow/tensorflow:latest-gpu-py3

%help
	Apptainer image with TensorFlow 1.7 and Keras running on python 3.5 with GPU support.

%post
	export PATH=/bin:/sbin:/usr/bin:/usr/sbin:$PATH
	pip3 install -U keras
	mkdir /nobackup /data /panfs

Instantiating a container from such an image would look like this:

$ apptainer exec --nv my-singularity-image.sif python -c "import tensorflow"

Alternatively, you can run a GPU-enabled image directly from Docker Hub. Here's an example SLURM script for running a GPU-enabled Tensorflow container on ACCRE GPUs:

#!/bin/bash
#SBATCH --account=MY_GPU_ACCOUNT
#SBATCH --partition=pascal
#SBATCH --gres=gpu:1
#SBATCH --mem=10G
#SBATCH --time=12:00:00

# Clone tensorflow repo to run a tutorial
git clone https://github.com/tensorflow/models.git
apptainer exec --nv docker://tensorflow/tensorflow:latest-gpu \
	python ./models/tutorials/image/mnist/convolutional.py

Again, we recommend you to use apptainer pull to build an image locally from docker hub for repeated usage.

Using Docker to build an image

Since Apptainer supports running Docker images, many users prefer to build docker image locally on their computer, then either create an image archive to transfer to the cluster using tools like scp, or upload the image to Docker Hub so it can be pulled directly from the cluster. If you have a container image already available in Docker Hub or any other repo hosting the Docker image, follow this instruction on how to run docker container in Apptainer.

Writing a Dockerfile

A Dockerfile is a text document containing all the commands a user would execute on the command line to assemble an image. Here's an example:

# 1. Use an official Python runtime as a parent image
FROM python:3.7-slim

# 2. Set the working directory in the container
WORKDIR /usr/src/app

# 3. Copy the current directory contents into the container at /usr/src/app
COPY . .

# 4. Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# 5. Make port 80 available to the world outside this container
EXPOSE 80

# 6. Define environment variable
ENV NAME World

# 7. Run app.py when the container launches
CMD ["python", "app.py"]

Creating and Running Docker Image

You can use docker build command to create a Docker image from the Dockerfile. Pass the directory on which you have the Dockerfile as an argument to docker build command to build the image. docker run command allows us to run that image as a container in local machine and check if the container is working as intended.

# This creates a docker image named my-python-app using the Dockerfile from current directory
docker build -t my-python-app .
docker run -p 4000:80 my-python-app

Now that you have built a container image in your local machine, you can transfer that image to the cluster to be able to run it through Apptainer. Here are the two recommended process you could follow to do that :

Option 1 : Creating a Docker Hub Account and Uploading the Image to Docker Hub

To create a sharable Docker container images, you can upload them to Docker Hub. Create a Docker Hub account and follow these steps:

Authenticate your Docker client to Docker Hub:

docker login

Tag your image to match your Docker Hub username:

docker tag my-python-app username/my-python-app

Upload your image to Docker Hub:

docker push username/my-python-app

Upon successfully publishing the docker image in Docker hub, you can follow this section to run the docker container.

Option 2 : Saving Docker Image and Running it with Apptainer

If you prefer not to use Docker Hub, you can save your Docker image as an archive, transfer it to your cluster, and run it using Apptainer. Follow these steps:

Save your Docker image as a tar archive

docker save -o my-python-app.tar my-python-app

Transfer the image archive to your cluster using scp

scp my-python-app.tar user@cluster-address:/path/to/destination

On the cluster, load and convert the Docker image using Apptainer

apptainer build my-python-app.sif docker-archive://my-python-app.tar

Run the container using Apptainer

apptainer run my-python-app.sif

Commonly Encountered Errors

Missing Libraries

Symptoms: Errors indicating that a library or dependency is not found when trying to run your application inside a container.

Possible Solutions:

  • Ensure all necessary libraries are listed in your requirements.txt (for Python) or the equivalent dependency file.
  • Double-check your Dockerfile to confirm the COPY command correctly transfers the dependency file and that the RUN command installs dependencies.
  • Verify that you are correctly binding paths using the -B flag:
apptainer run -B /accre,/cvmfs,/data/your_datapath:/workdir/data/ container.sif

Broken Links/Symlinks

Symptoms: The application fails because links point to files or directories that do not exist within the container's filesystem.

Possible Solutions:

  • Ensure that the path is mounted properly to the container.
  • Ensure that the paths you are mounting exist and are accessible on the host system
  • Confirm that the file or directory the link points to exists within the container.

Environment Variables Not Set

Symptoms: Application behavior suggests environment variables are missing or incorrect.

Possible Solutions:

  • Use the ENV instruction (Docker) or %environment section (Apptainer) to set variables.
  • Set environment variables at runtime:
env_var1=val1 env_var2=val2 apptainer run -e "VARIABLE_NAME=value" my-image

Multiple Environment Variables Overlapping

If you have Conda or pip installations in your profile folder, they might interfere with the container’s setup.

Solution:

apptainer run --cleanenv ./lolcow.sif

ACCRE Apptainer GitHub Repository

ACCRE maintains an Apptainer GitHub repository with more examples. While we continuously work to update the content, due to the rapidly evolving nature of technology, some content in our GitHub Repository may be outdated. Therefore, we also encourage users to contribute their own examples to the repository!