Zeljko's Blog

Tensorflow Dockerfile

Created: 2023-04-07
Last Modified: 2025-01-29

I have to use Tensorflow right now. The official documentation recommends either to use conda or docker. I went for docker because I feel more comfortable it than conda. Here I wanted to dump a version of a usable Dockerfile which can be refined:

FROM tensorflow/tensorflow:2.10.1-gpu

ARG USERNAME="containeruser"
ARG USERID=1000
ARG GROUPID=1000

RUN apt-get update && \
    apt-get install -y sudo &&\
    groupadd -g $GROUPID -o $USERNAME && \
    useradd -m -u $USERID -g $GROUPID -o -s /bin/bash $USERNAME

USER $USERNAME

RUN mkdir -p /home/$USERNAME/project

WORKDIR /home/$USERNAME/project

COPY requirements.in requirements_prefilter.in

RUN grep -v -I -E 'tensorflow|cudnn' requirements_prefilter.in > requirements.in && \
    rm requirements_prefilter.in && \
    pip install -r requirements.in

Then I build it the following way:

docker build --build-arg USERID=$(id -u) --build-arg GROUPID=$(id -g) -t mytensorflow .

And run it this way:

docker run --gpus all -v "$(pwd):/data" -it --rm mytensorflow bash

Here are two important things to watch out for. Firstly you need to pay attention to the user-id and group-id. Secondly you need to pay attention not to install other tensorflow/cuda packages. That is why I grep them out. Also, you can’t push this container to a registry. This is because the user-id and group-id of the end-user of this container might not match the ones on the build system.