在这篇教程文章中,将演示如何在docker中运行python应用程序。首先需要创建Dockerfile,可参考以下步骤,并一步步实践。
zyiz@ubuntu:~$ mkdir -p /home/zyiz/docker/docker-python-app
zyiz@ubuntu:~$ cd /home/zyiz/docker/docker-python-app
Dockerfile
的Dockerfile文件FROM python COPY . /home/zyiz/src CMD ["python", "/home/zyiz/src/index.py"]
创建一个在Docker容器中执行的python文件:index.py
。
print("Hello from python file");
要创建这个python应用程序的Docker映像,需要使用以下Docker命令。
zyiz@ubuntu:~/docker/docker-python-app$ sudo docker build -t python-app .
执行结果如下 -
zyiz@ubuntu:~/docker/docker-python-app$ docker build -t python-app . Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.29/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=python-app&target=&ulimits=null: dial unix /var/run/docker.sock: connect: permission denied zyiz@ubuntu:~/docker/docker-python-app$ sudo docker build -t python-app . [sudo] password for zyiz: Sending build context to Docker daemon 3.072kB Step 1/3 : FROM python latest: Pulling from library/python 10a267c67f42: Already exists fb5937da9414: Pull complete 9021b2326a1e: Pull complete dbed9b09434e: Pull complete ea8a37f15161: Pull complete 9fb634154ace: Pull complete 6df6941e6752: Pull complete df67ecfc860b: Pull complete Digest: sha256:b2dfd12f7fb4997345b11b74b154849d0549e270221030cd0450b85b7f6c0e92 Status: Downloaded newer image for python:latest ---> b6cc5d70bc28 Step 2/3 : COPY . /src ---> 3f5ca1d2cf05 Removing intermediate container dc2c6cc3df67 Step 3/3 : CMD python /src/index.py ---> Running in 998b7f2b3ed2 ---> bc4ea57dd1b5 Removing intermediate container 998b7f2b3ed2 Successfully built bc4ea57dd1b5 Successfully tagged python-app:latest zyiz@ubuntu:~/docker/docker-python-app$
可以通过以下命令查看所有可用的Docker映像。
zyiz@ubuntu:~/docker/docker-python-app$ docker images
执行上面命令,结果如下 -
zyiz@ubuntu:~/docker/docker-python-app$ sudo docker images REPOSITORY TAG IMAGE ID CREATED SIZE python-app latest bc4ea57dd1b5 3 minutes ago 689MB php-app latest 7bd0234c2184 33 hours ago 390MB <none> <none> 0420419feb44 33 hours ago 390MB <none> <none> ca59a5a4f3fb 33 hours ago 390MB <none> <none> c2e626f9d9c6 34 hours ago 390MB java-app latest bd61e7f49911 2 days ago 643MB php 7.0-apache a4322279ced1 2 days ago 390MB python latest b6cc5d70bc28 3 weeks ago 689MB java 8 d23bdf5b1b1b 4 months ago 643MB hello-world latest 48b5124b2768 4 months ago 1.84kB zyiz@ubuntu:~/docker/docker-python-app$
创建Docker映像后,现在可以使用以下命令来运行它。
zyiz@ubuntu:~/docker/docker-python-app$ sudo docker run python-app
上述命令运行Docker映像并执行python文件。 执行后,产生结果如下输出所示。
zyiz@ubuntu:~/docker/docker-python-app$ sudo docker run python-app Hello from python file zyiz@ubuntu:~/docker/docker-python-app$