How can I install python modules in a docker image

2019-04-02 11:07发布

问题:

I have an image called: Image and a running container called: container. I want to install pytorch and anacoda. what's the easiest way to do this? Do I have to change the dockerfile and build a new image? Thanks a lot.

回答1:

Yes, the best thing is to build your image in such a way it has the python modules are in there.

Here is an example. I build an image with the build dependencies:

$ docker build -t oz123/alpine-test-mycoolapp:0.5 - < Image
Sending build context to Docker daemon  2.56 kB
Step 1 : FROM alpine:3.5
 ---> 88e169ea8f46
Step 2 : ENV MB_VERSION 3.1.4
 ---> Running in 4587d36fa4ae
 ---> b7c55df49803
Removing intermediate container 4587d36fa4ae
Step 3 : ENV CFLAGS -O2
 ---> Running in 19fe06dcc314
 ---> 31f6a4f27d4b
Removing intermediate container 19fe06dcc314
Step 4 : RUN apk add --no-cache python3 py3-pip gcc python3-dev py3-cffi    file git curl autoconf automake py3-cryptography linux-headers musl-dev libffi-dev openssl-dev build-base
 ---> Running in f01b60b1b5b9
fetch http://dl-cdn.alpinelinux.org/alpine/v3.5/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.5/community/x86_64/APKINDEX.tar.gz
(1/57) Upgrading musl (1.1.15-r5 -> 1.1.15-r6)
(2/57) Upgrading zlib (1.2.8-r2 -> 1.2.11-r0)
(3/57) Installing m4 (1.4.17-r1)
(4/57) Installing perl (5.24.0-r0)
(5/57) Installing autoconf (2.69-r0)
(6/57) Installing automake (1.15-r0)
(7/57) Installing binutils-libs (2.27-r1)
...

Note, I am installing Python's pip inside the image, so later I can download packages from pypi. Packages like numpy might require a C compiler and tool chain, so I am installing these too.

After building the packages which require the build tools chain I remove the tool chain packages:

RUN apk del file pkgconf autoconf m4 automake perl g++ libstdc++

After you have your base image, you can run your application code in an image building on top of it:

$ cat Dockerfile

    FROM oz123/alpine-test-mycoolapp
    ADD . /code
    WORKDIR /code
    RUN pip3 install -r requirements.txt -r requirements_dev.txt
    RUN pip3 install -e .
    RUN make clean
    CMD ["pytest", "-vv", "-s"]

I simply run this with docker.