Docker 是一個開源的應用容器引擎,讓開發者可以打包他們的應用以及依賴包到一個可移植的容器中,然后發布到任何流行的 Linux 機器上,也可以實現虛擬化。容器是完全使用沙箱機制,相互之間不會有任何接口。--這段來自百度百科
下面開始正文:
先介紹下我使用的環境
1 Ubuntu 16.04.3 LTS 2 Docker version 17.06.1-CE
開始學習docker的時候構建tensorflow環境,直接使用命令 docker search tensorflow 查找鏡像。
henrry@henrry:~/docker$ docker search tensorflow NAME DESCRIPTION STARS OFFICIAL AUTOMATED tensorflow/tensorflow Official docker images for deep learning f... 503 xblaster/tensorflow-jupyter Dockerized Jupyter with tensorflow 39 [OK] jupyter/tensorflow-notebook Jupyter Notebook Scientific Python Stack w... 17
然后使用 docker pull tensorflow/tensorflow 下載鏡像,但是這個鏡像里面使用的是python2,而我想學習使用的又是python3,不爽,所以換。
有兩種方法可以構建自己的docker 鏡像,一種就是下載系統基礎鏡像,然后創建容器,在容器中安裝自己需要的軟件,完成后,將容器重新提交到鏡像。還有一種方法就是使用Dockerfile構建鏡像。
方法一:
第一步:先 docker search ubuntu 查找到ubuntu的鏡像。
henrry@henrry:~/docker$ docker search ubuntu NAME DESCRIPTION STARS OFFICIAL AUTOMATED ubuntu Ubuntu is a Debian-based Linux operating s... 6476 [OK] dorowu/ubuntu-desktop-lxde-vnc Ubuntu with openssh-server and NoVNC 128 [OK]
第二步: docker pull ubuntu ,完成之后使用 docker images 查看pull下來的鏡像,很小只有120M。
henrry@henrry:~/docker$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest ccc7a11d65b1 2 weeks ago 120MB
第三步: docker run -ti -d --name tensorflow ubuntu bash 創建容器。
henrry@henrry:~/docker$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 06cfd359fc0f ubuntu "bash" 3 days ago Up 1 second tensorflow
第四步: docker exec -ti tensorflow bash 進入容器。
henrry@henrry:~/docker$ docker exec -ti tensorflow bash
root@06cfd359fc0f:/#
第五步:就是在內部使用apt 安裝軟件了,不過在安裝軟件之前需要先 apt update 下,要不使用apt 就無法安裝軟件包。
下面直接給出軟件的安裝命令。這些安裝命令都是tensorflow官網上的,如果安裝過程中出現啥問題,點這里,然后查找"Installing with native pip",看下官網的文檔。還有一點需要注意的就是ubuntu的基礎鏡像里面沒有vim,所以安裝的時候也將vim裝上。
1 apt update 2 apt install -y python3-pip python3-dev vim 3 pip3 install tensorflow 4 pip3 install tensorflow-gpu #這個我目前還沒有用到,所以我沒有安裝
安裝完成之后,使用下面這塊代碼測試下:
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 4 import tensorflow as tf 5 hello = tf.constant('Hello, TensorFlow!') 6 sess = tf.Session() 7 print(sess.run(hello))
最后一步:就是將安裝好軟件的容器,提交到鏡像中。使用命令 docker commit tensorflow tensorflow:20170827
henrry@henrry:~/docker$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE tensorflow 20170827 b7847f7b09a6 3 days ago 1.14GB ubuntu latest ccc7a11d65b1 2 weeks ago 120MB
方法二:
使用Dockerfile文件構建鏡像,這個比較簡單,下面直接貼出來Dockerfile文件內容:
# 構建tensorflow 環境 FROM ubuntu MAINTAINER henrry # 安裝python 和 pip RUN apt update \
&& apt install -y python3-pip python3-dev vim \
&& pip3 install --upgrade pip \ && pip3 install tensorflow \
&& pip3 install tensorflow-gpu \
&& ln -s /usr/bin/python3 /usr/bin/python \ && ln -s /usr/bin/pip3 /usr/bin/pip # 映射端口 EXPOSE 8888
# 添加文件 ADD vimrc /root/.vimrc
文件創建好之后,名字改成Dockerfile,然后執行命令 docker build -t tensorflow:20170827 . 構建名稱為 tensorflow TAG為20170827的鏡像。然后就可以創建容器,進行操作了。
好了,兩個方法都可以構建成功,親測。。。