Docker 是 dotCloud 最近几个月刚宣布的开源引擎,旨在提供一种应用程序的自动化部署解决方案,简单的说就是,在 Linux 系统上迅速创建一个容器(类似虚拟机)并在容器上部署和运行应用程序,并通过配置文件可以轻松实现应用程序的自动化安装、部署和升级,非常方便。因为使用了容器,所以可以很方便的把生产环境和开发环境分开,互不影响,这是 docker 最普遍的一个玩法。更多的玩法还有大规模 web 应用、数据库部署、持续部署、集群、测试环境、面向服务的云计算、虚拟桌面 VDI 等等。
Docker 使用 Go 语言编写,用 cgroup 实现资源隔离,容器技术采用 LXC. LXC 已经足够成熟,被多个主流 PaaS 服务商采用(比如 dotCloud),国内的一些互联网公司也在用(比如腾讯)。虽然都是企图解决自动化部署方面的问题,Docker 的解决方式有别于我们常提到的 Puppet/Chef,他们虽然走的是不同的路,但也可以拿来一起用。
安装 (ubuntu 12.04)
Due to a bug in LXC, Docker works best on the 3.8 kernel. Precise comes with a 3.2 kernel, so we need to upgrade it. The kernel you’ll install when following these steps comes with AUFS built in. We also include the generic headers to enable packages that depend on them, like ZFS and the VirtualBox guest additions.
sudo apt-get install python-software-properties
sudo apt-get install linux-image-generic-lts-raring linux-headers-generic-lts-raring
sudo reboot
添加docker源并安装docker
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
sudo sh -c "echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
sudo apt-get update
sudo apt-get install lxc-docker
上面两步也可以替换成执行curl -s https://get.docker.io/ubuntu/ | sudo sh,更简单。
创建容器
首先从https://index.docker.io/下载一个预定义的镜像
sudo docker pull ubuntu
启动一个容器:
sudo docker run -i -t ubuntu /bin/bash
Starting a long-running worker process
# Start a very useful long-running process
JOB=$(sudo docker run -d ubuntu /bin/sh -c "while true; do echo Hello world; sleep 1; done")
# Collect the output of the job so far
sudo docker logs $JOB
# Kill the job
sudo docker kill $JOB
Bind a service on a TCP port
# Bind port 4444 of this container, and tell netcat to listen on it
JOB=$(sudo docker run -d -p 4444 ubuntu:12.10 /bin/nc -l 4444)
# Which public port is NATed to my container?
PORT=$(sudo docker port $JOB 4444 | awk -F: '{ print $2 }')
# Connect to the public port
echo hello world | nc 127.0.0.1 $PORT
# Verify that the network connection worked
echo "Daemon received: $(sudo docker logs $JOB)"
Committing (saving) a container state¶
Save your containers state to a container image, so the state can be re-used.
When you commit your container only the differences between the image the container was created from and the current state of the container will be stored (as a diff). See which images you already have using the docker images command.
# Commit your container to a new named image
sudo docker commit <container_id> <some_name>
# List your containers
sudo docker images
You now have a image state from which you can create new instances.