Running Jupyter Notebook in Ubuntu Docker Container

Recently I attempted to run Jupyter Notebook in Ubuntu Docker container for a project requiring OpenCV and PyTorch. Sharing the Docker configuration files I used here.

docker-compose.yml

version: "3"

services: 
  ml-docker:
    build: .
    container_name: ML-docker
    stdin_open: true
    tty: true
    ports:
      - '8888:8888'
    volumes: 
      - $PWD/shared:/shared

Jupyter notebook listens on port 8888 by default. So, I am mapping it to the same port on the host machine. I have also created a folder ‘shared’ in the same folder where above docker-compose.yml is located. And I have made this folder accessible to the container using volumes declaration. The above file instructs docker to build Dockerfile in the same folder. Content of the Dockerfile is as follows –

Dockerfile

FROM ubuntu

RUN apt-get update

#required for OpenCV
RUN apt-get install -y libgl1-mesa-glx 
RUN apt-get install -y libglib2.0-0

RUN apt install -y python3
RUN apt install -y python3-pip
RUN python3 -m pip install torch torchvision
RUN python3 -m pip install transformers 
RUN python3 -m pip install numpy pandas matplotlib jupyter opencv-python

Base image is ubuntu. It then has commands to install Python3 and required libraries for OpenCV and PyTorch.

To start the container, run following command

docker-compose up

In a separate terminal window, run “docker ps” to get the id of the newly launched Docker container and attach to that container using following command –

docker attach <replace-with-docker-id-from-ps-command>

See my blog on Docker for detailed Docker commands or refer to Docker documentation.

Run following Jupyter command from the container –

jupyter notebook --allow-root --ip="0.0.0.0"

—allow-root allows jupyter notebook to run as root, which by default is not allowed. —ip=“0.0.0.0” allows it to listen to requests from all IP addresses. This will allow host environment to make request to jupyter notebook from the browser.

Copy the URL with token from Jupyter notebook console output and paste it in the browser in the host environment. You can now create new notebooks (which will be created in ‘shared’ folder in your host environment) and execute them from the host environment.

-Ram Kulkarni

Leave a Reply

Social