How to add Python libraries to Docker image

To customize an image you generally want to create a new one using the existing image as a base. In Docker it is extremely common to create custom images when existing ones don't quite do what you want. By basing your images off public ones you can add your own customizations without having to repeat (or even know) what the base image does.

  1. Add the necessary steps to a new Dockerfile.

    FROM tensorflow/tensorflow:latest-gpu-jupyter
    
    RUN <extra install steps>
    COPY <extra files>
    

    RUN and COPY are examples of instructions you might use. RUN will run a command of your choosing such as RUN pip install matplotlib. COPY is used to add new files from your machine to the image, such as a configuration file.

  2. Build and tag the new image. Give it a new name of your choosing. I'll call it my-customized-tensorflow, but you can name it anything you like.

    Assuming the Dockerfile is in the current directory, run docker build:

    $ docker build -t my-customized-tensorflow .
    
  3. Now you can use my-customized-tensorflow as you would any other image.

    $ docker run my-customized-tensorflow
    

Add this to your Dockerfile after pulling the image:

RUN python -m pip install matplotlib

There are multiple options:

  • Get into the container and install dependencies (be aware that this changes will be lost when recreating the container):

    docker exec <your-container-id> /bin/bash
    

    That should open an interactive bash. Then install the dependencies (pip or conda).

  • Another alternative, is to add it during build time (of the image). That is adding the instruction RUN into a Dockerfile

All dependencies are installed using python default tools (i.e: pip, conda)

Tags:

Python

Docker