/ #docker #C++ 

Adding Environment Variables for Arbitrary Users in Docker

Goal

When building a Docker image, we often install various C++ libraries. However, when working inside the container as a non-root user, header files may not be automatically included in the default search paths, which can be inconvenient.

We want to configure this neatly during the image build (inside the Dockerfile). However, the ENV directive only sets environment variables directly or for the root context, and might not always propagate properly to custom non-root users added later in certain shell sessions.

We want a reliable way to add environment variables for any user logging in.

Solution

While there may be multiple ways to achieve this, placing an initialization .sh script under /etc/profile.d/ inside the container works effectively. All scripts in this directory are executed upon login.

Below is an excerpt from a Dockerfile installing C++ Eigen and Boost libraries:

# Install Eigen
RUN apt-get install -y libeigen3-dev
# Install Boost
RUN apt-get install -y libboost-dev

# Add path (script)
RUN touch /etc/profile.d/my_init.sh && \
    echo "export CPLUS_INCLUDE_PATH=/usr/include/eigen3/:/usr/include/boost/" \
    >> /etc/profile.d/my_init.sh