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
    
Answer from John Kugelman on Stack Overflow
🌐
PyPI
pypi.org › project › docker
docker · PyPI
Maintainer: Docker Inc. ... A Python library for the Docker Engine API.
      » pip install docker
    
Published   May 23, 2024
Version   7.1.0
🌐
Docker Hub
hub.docker.com › _ › python
python - Official Image | Docker Hub
Published image artifact details: repo-info repo's repos/python/ directory⁠ (history⁠) (image metadata, transfer size, etc) Image updates: official-images repo's library/python label⁠ official-images repo's library/python file⁠ (history⁠)
🌐
GitHub
github.com › docker › docker-py
GitHub - docker/docker-py: A Python library for the Docker Engine API · GitHub
A Python library for the Docker Engine API. Contribute to docker/docker-py development by creating an account on GitHub.
Starred by 7.2K users
Forked by 1.7K users
Languages   Python
🌐
GitHub
github.com › docker-library › python
GitHub - docker-library/python: Docker Official Image packaging for Python · GitHub
See the Docker Hub page for the full readme on how to use this Docker image and for information regarding contributing and issues. The full image description on Docker Hub is generated/maintained over in the docker-library/docs repository, ...
Starred by 2.7K users
Forked by 1.1K users
Languages   Dockerfile 50.3% | Shell 49.7%
🌐
Medium
medium.com › @shuklashubh818 › exploring-docker-py-a-python-library-for-docker-automation-8df5bc727fbe
Exploring Docker-Py: A Python Library for Docker Automation | by Shubh Prakash Shukla | Medium
February 15, 2024 - Docker-Py is a Python client library that allows developers to communicate with the Docker Engine’s Remote API programmatically.
🌐
PyPI
pypi.org › project › docker-py
docker-py · PyPI
Python client for Docker. ... A Python library for the Docker Remote API.
      » pip install docker-py
    
Published   Nov 02, 2016
Version   1.10.6
Find elsewhere
🌐
Docker
docker-py.readthedocs.io › en › stable › containers.html
Containers — Docker SDK for Python 7.1.0 documentation
A Python library for the Docker Engine API · Client · Configs · Containers · Container objects · Images · Networks · Nodes · Plugins · Secrets · Services · Swarm · Volumes · Low-level API · Using TLS · User guides and tutorials · Changelog · Run and manage containers on the server.
🌐
TutorialsPoint
tutorialspoint.com › python-library-api-for-docker
Python Library API for Docker
You can access, manage and manipulate docker objects such as containers, images, clusters, swarms, etc. using a python library API. You can do pretty much anything that docker commands let you do. This comes very handy when you are using a python
🌐
Docker
docker.com › blog › how-to-dockerize-your-python-applications
How to “Dockerize” Your Python Applications | Docker
These commands—and numerous others within the library—help update your active applications. You can also use Docker Compose to handle environment variables—which comes bundled within Docker Desktop.
Published   November 6, 2024
🌐
Bhaskarvk
bhaskarvk.github.io › docker
Wraps Docker Python SDK • docker
mkvirtualenv --python=/usr/bin/python3 docker workon docker pip install docker # Test the SDK againsts a locally running docker # You should have a locally running docker for this. python -c 'import docker; print(docker.from_env().version())' You should see something like below, provided you had a locally running docker engine. {'Os': 'linux', 'Arch': 'amd64', 'KernelVersion': '4.10.0-24-generic', 'GitCommit': '02c1d87', 'Version': '17.06.0-ce', 'BuildTime': '2017-06-23T21:19:04.990631145+00:00', 'MinAPIVersion': '1.12', 'GoVersion': 'go1.8.3', 'ApiVersion': '1.30'} reticulate::use_virtualenv("docker") library(docker) client <- docker$from_env() s <- client$containers$run("alpine", 'echo -n "Hello World!"', remove=TRUE) print(s$decode("UTF-8")) #> [1] "Hello World!"
🌐
Medium
medium.com › @pradeepkr848115 › docker-python-library-a-comprehensive-guide-79dedaf0a0aa
Docker Python Library: A Comprehensive Guide | by Pradeep Kumar | Medium
February 16, 2024 - Docker is a popular platform used to develop, ship, and run applications within containers. The Docker Python library, also known as docker-py, is a Python SDK for the Docker Engine API.
🌐
Medium
medium.com › @saba_fatima › docker-library-in-python-a6755e6f4e75
Docker Library in Python. Introduction to Docker Library in… | by Saba Fatima | Medium
February 13, 2024 - Define your application stack in a `docker-compose.yml` file and interact with it using Python. By exploring the Docker library in Python and utilizing the provided code snippets, developers can seamlessly integrate Docker features into their Python applications, enabling efficient containerization and management of their software environments.
🌐
GitHub
github.com › aio-libs › aiodocker
GitHub - aio-libs/aiodocker: Python Docker API client based on asyncio and aiohttp · GitHub
pip install -U build python -m build --sdist --wheel ... import asyncio import aiodocker async def list_things(docker): print('== Images ==') for image in (await docker.images.list()): tags = image['RepoTags'][0] if image['RepoTags'] else '' print(image['Id'], tags) print('== Containers ==') for container in (await docker.containers.list()): print(f" {container._id}") async def run_container(docker): print('== Running a hello-world container ==') container = await docker.containers.create_or_replace( config={ 'Cmd': ['/bin/ash', '-c', 'echo "hello world"'], 'Image': 'alpine:latest', }, name='testing', ) await container.start() logs = await container.log(stdout=True) print(''.join(logs)) await container.delete(force=True) async def main(): docker = aiodocker.Docker() await list_things(docker) await run_container(docker) await docker.close() if __name__ == "__main__": asyncio.run(main())
Starred by 523 users
Forked by 113 users
Languages   Python
Top answer
1 of 5
4

During development it is IMO perfectly fine to map/mount the hostdirectory with your ever changing sources into the Docker container. The rest (the python version, the other libraries you are dependent upon you can all install in the normal way in the the docker container.

Once stabilized I remove the map/mount and add the package to the list of items to install with pip. I do have a separate container running devpi so I can pip-install packages whether I push them all the way to PyPI or just push them to my local devpi container.

Doing speed up container creation even if you use the common (but more limited) python [path_to_project/setup.py] develop. Your Dockerfile in this case should look like:

 # the following seldom changes, only when a package is added to setup.py
 COPY /some/older/version/of/project/plus/dependent/packages /older/setup
 RUN pip /older/setup/your_package.tar.gz

 # the following changes all the time, but that is only a small amount of work
 COPY /latest/version/of/project     
 RUN python [path_to_project/setup.py] develop

If the first copy would result in changes to files under /older/setup then the container gets rebuilt from there.

Running python ... develop still makes more time and you need to rebuild/restart the container. Since my packages all can also be just copied in/linked to (in addition to be installed) that is still a large overhead. I run a small program in the container that checks if the (mounted/mapped) sources change and then reruns anything I am developing/testing automatically. So I only have to save a new version and watch the output of the container.

2 of 5
3

For deployment/distribution, it would be seamless to have a docker image for your package. If not as an image, you need to transfer you source code to the environment where it needs to be run, configure a volume to have the source inside container so that it can be built etc., With image its just pull and run a container out of it.

But for ease and to get rid of manual steps in building the image, consider using docker-compose.

docker-compose.yml may look like this:

ml_experiment:
  build: <path/to/Dockerfile>
  volumes:
    - ~/data/:/data
  command: ["python", "run_ML_experiment_file.py"] 

Now to build an image and bring up a container you just need to do

docker-compose up --build

The option --build is must to rebuild the image each time, else docker-compose chooses to use the image already built

Refer https://docs.docker.com/compose/

🌐
ECR Public Gallery
gallery.ecr.aws › docker › library › python
Amazon ECR Public Gallery - Docker/library/python
For many simple, single file projects, you may find it inconvenient to write a complete Dockerfile. In such cases, you can run a Python script by using the Python Docker image directly: $ docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp public.ecr.aws/docker/library/python:3 python your-daemon-or-script.py
🌐
Docker
docker.com › blog › containerized-python-development-part-1
Containerized Python Development - Part 1 | Docker
May 24, 2024 - $ docker build -t myimage . Sending build context to Docker daemon 6.144kB Step 1/6 : FROM python:3.8 3.8.3-alpine: Pulling from library/python …
Top answer
1 of 4
91

Recommended base image

As suggested in my comment, you could write a Dockerfile that looks like:

FROM python:3

RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir nibabel pydicom matplotlib pillow med2image
    # Note: we had to merge the two "pip install" package lists here, otherwise
    # the last "pip install" command in the OP may break dependency resolution…

CMD ["cat", "/etc/os-release"]

And the command example above could confirm at runtime (docker build --pull -t test . && docker run --rm -it test) that this image is based on the GNU/Linux distribution "Debian stable".

Generic Dockerfile template

Finally to give a comprehensive answer, note that a good practice regarding Python dependencies consists in specifying them in a declarative way in a dedicated text file (in alphabetical order, to ease review and update) so that for your example, you may want to write the following file:

requirements.txt

matplotlib
med2image
nibabel
pillow
pydicom

and use the following generic Dockerfile

FROM python:3

WORKDIR /usr/src/app

COPY requirements.txt ./

RUN pip install --no-cache-dir --upgrade pip \
  && pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "./your-daemon-or-script.py"]

To be more precise, this is the approach suggested in the documentation of the Docker official image python, §. How to use this image

2 of 4
48

Some of the other answers/comments are suggesting to change your base image but if you want to keep your ubuntu 16.04 you can also simply specify your version of pip/python to use pip3 or pip3.5 like shown below.

FROM ubuntu:16.04

RUN apt-get update && apt-get install -y --no-install-recommends \
    python3.5 \
    python3-pip \
    && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

RUN pip3 install nibabel pydicom matplotlib pillow
RUN pip3 install med2image