Docker is an open-source project to easily create lightweight, portable, self-sufficient containers from any application.
安装
(略),见官方文档
ubuntu安装很容易,不过要注意内核版本,至少3.8以上。安装成功后,使用lxc-checkconfig检查下LXC配置是否正常。
避免sudo docker
docker命令跟默认docker daemon创建的unix socket通讯都需要sudo权限,这可以通过创建docker组来解决。
sudo groupadd docker #将当前用户加入docker组 sudo gpasswd -a ${USER} docker #重启docker服务 sudo service docker restart
这样一来,docker命令的执行就不再需要sudo权限。如果没有生效,退出重新登陆即可。
hello world
跑个ubuntu的image试试看:
docker pull ubuntu docker run ubuntu /bin/echo hello world
这将启动一个container加载ubuntu image并执行echo程序,打印hello world,然后退出。”docker ps”可查看container列表。
lxc-start: No cgroup mounted on the system
这个错误是因为cgroup没有mount,建议mount到/sys/fs/cgroup目录。首先编辑/etc/fstab文件,加入下面这行配置:
none /sys/fs/cgroup cgroup defaults 0 0
接下来创建目录,并mount:
sudo mkdir -p /sys/fs/cgroup sudo mount /sys/fs/cgroup
创建一个运行Node.js应用的ubuntu image
官方给的例子是创建centos上运行node.js应用,具体看这里。
下面尝试用ubuntu创建下。
Node.js应用
创建一个src目录,存放node.js应用源码和配置
mkdir src touch src/package.json touch src/index.js
其中package.json内容:
{ "name": "docker-ubuntu-hello", "private": true, "version": "0.0.1", "description": "Node.js Hello World app on ubuntu using docker", "author": "Daniel Gasienica, Dennis ", "dependencies": { "express": "3.2.4" } }
index.js就是使用express框架渲染首页hello world:
var express = require('express'); // Constants var PORT = 8080; // App var app = express(); app.get('/', function (req, res) { res.send('Hello Worldn'); }); app.listen(PORT) console.log('Running on http://localhost:' + PORT);
创建Dockerfile
Dockerfile文件配置image众多参数,例如parent image是什么,执行哪些安装命令,拷贝应用文件,导出TCP端口等等。与src目录统计创建文件名为Dockerfile,内容如下:
FROM ubuntu:12.10 RUN apt-get update RUN apt-get install -y python-software-properties python g++ make software-properties-common RUN add-apt-repository ppa:chris-lea/node.js RUN apt-get update RUN apt-get install -y nodejs ADD ./src /src RUN cd /src; npm install EXPOSE 8080 CMD ["node", "/src/index.js"]
我们采用官方提供的ubuntu 12.10的image做为os版本,接下来通过RUN指令安装node.js,然后用ADD指令将src目录拷贝到image的/src目录下,并在/src目录下执行npm install安装node.js依赖包,导出应用监听的8080端口到container外,最终通过CMD指令启动node.js应用。
关于Dockerfile指令参考这里。
构建Image
执行下列指令:
docker build -t dennis/node-js .
通过-t选项为这个image打上一个tag,在构建完成后,通过docker images列出所有的image的时候,可以看到你刚创建的image: dennis/node-js
运行container并测试
有了image,就可以从这个image启动一个container来运行node.js应用:
docker run -p 47516:8080 -d dennis/node-js
我们将container内node.js应用监听的8080端口通过-p选项桥接到宿主机器(host machine)的47516端口,也就是说你可以通过47516端口能问到容器内的node.js应用。尝试下:
curl -X GET http://localhost:47516/
输出hello world。
本例子的源码已经放到Github。
网友评论已有0条评论, 我也要评论