├── .gitignore
├── Changelog.md
├── LICENSE.txt
├── Makefile
├── README.md
├── Vagrantfile
├── image
├── 00_regen_ssh_host_keys.sh
├── Dockerfile
├── buildconfig
├── cleanup.sh
├── config
│ ├── sshd_config
│ └── syslog_ng_default
├── enable_insecure_key
├── insecure_key
├── insecure_key.ppk
├── insecure_key.pub
├── my_init
├── prepare.sh
├── runit
│ ├── cron
│ ├── sshd
│ └── syslog-ng
├── setuser
├── system_services.sh
└── utilities.sh
└── test
├── runner.sh
└── test.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .vagrant
3 |
--------------------------------------------------------------------------------
/Changelog.md:
--------------------------------------------------------------------------------
1 | ## 0.9.9 (not yet released)
2 |
3 | * Fixed a problem with rssh. (Slawomir Chodnicki)
4 |
5 | ## 0.9.8 (release date: 2014-02-26)
6 |
7 | * Fixed a regression in `my_init` which causes it to delete environment variables passed from Docker.
8 | * Fixed `my_init` not properly forcing Runit to shut down if Runit appears to refuse to respond to SIGTERM.
9 |
10 | ## 0.9.7 (release date: 2014-02-25)
11 |
12 | * Improved and fixed bugs in `my_init` (Thomas LÉVEIL):
13 | * It is now possible to enable the insecure key by passing `--enable-insecure-key` to `my_init`. This allows users to easily enable the insecure key for convenience reasons, without having the insecure key enabled permanently in the image.
14 | * `my_init` now exports environment variables to the directory `/etc/container_environment` and to the files `/etc/container_environment.sh`, `/etc/container_environment.json`. This allows all applications to query what the original environment variables were. It is also possible to change the environment variables in `my_init` by modifying `/etc/container_environment`. More information can be found in the README, section "Environment variables".
15 | * Fixed a bug that causes it not to print messages to stdout when there is no pseudo terminal. This is because Python buffers stdout by default.
16 | * Fixed an incorrectly printed message.
17 | * The insecure key is now also available in PuTTY format. (Thomas LÉVEIL)
18 | * Fixed `enable_insecure_key` removing already installed SSH keys. (Thomas LÉVEIL)
19 | * The baseimage-docker image no longer EXPOSEs any ports by default. The EXPOSE entries were originally there to enable some default guest-to-host port forwarding entries, but in recent Docker versions they changed the meaning of EXPOSE, and now EXPOSE is used for linking containers. As such, we no longer have a reason to EXPOSE any ports by default. Fixes GH-15.
20 | * Fixed syslog-ng not being able to start because of a missing afsql module. Fixes the issue described in [pull request 7](https://github.com/phusion/baseimage-docker/pull/7).
21 | * Removed some default Ubuntu cron jobs which are not useful in Docker containers.
22 | * Added the logrotate service. Fixes GH-22.
23 | * Fixed some warnings in `/etc/my_init.d/00_regen_ssh_host_keys.sh`.
24 | * Fixed some typos in the documentation. (Dr Nic Williams, Tomer Cohen)
25 |
26 | ## 0.9.6 (release date: 2014-02-17)
27 |
28 | * Fixed a bug in `my_init`: child processes that have been adopted during execution of init scripts are now properly reaped.
29 | * Much improved `my_init`:
30 | * It is now possible to run and watch a custom command, possibly in addition to running runit. See "Running a one-shot command in the container" in the README.
31 | * It is now possible to skip running startup files such as /etc/rc.local.
32 | * Shutdown is now much faster. It previously took a few seconds, but it is now almost instantaneous.
33 | * It ensures that all processes in the container are properly shut down with SIGTERM, even those that are not direct child processes of `my_init`.
34 | * `setuser` now also sets auxilliary groups, as well as more environment variables such as `USER` and `UID`.
35 |
36 | ## 0.9.5 (release date: 2014-02-06)
37 |
38 | * Environment variables are now no longer reset by runit. This is achieved by running `runsvdir` directly instead of through Debian's `runsvdir-start`.
39 | * The insecure SSH key is now disabled by default. You have to explicitly opt-in to use it.
40 |
41 | ## 0.9.4 (release date: 2014-02-03)
42 |
43 | * Fixed syslog-ng startup problem.
44 |
45 | ## 0.9.3 (release date: 2014-01-31)
46 |
47 | * It looks like Docker changed their Ubuntu 12.04 base image, thereby breaking our Dockerfile. This has been fixed.
48 | * The init system (`/sbin/my_init`) now supports running scripts during startup. You can put startup scripts `/etc/my_init.d`. `/etc/rc.local` is also run during startup.
49 | * To improve security, the base image no longer contains pregenerated SSH host keys. Instead, users of the base image are encouraged to regenerate one in their Dockerfile. If the user does not do that, then random SSH host keys are generated during container boot.
50 |
51 | ## 0.9.2 (release date: 2013-12-11)
52 |
53 | * Fixed SFTP support. Thanks Joris van de Donk!
54 |
55 | ## 0.9.1 (release date: 2013-11-12)
56 |
57 | * Improved init process script (`/sbin/my_init`): it now handles shutdown correctly. Previously, `docker stop` would not have any effect on `my_init`, causing the whole container to be killed with SIGKILL. The new init process script gracefully shuts down all runit services, then exits.
58 |
59 | ## 0.9.0 (release date: 2013-11-12)
60 |
61 | * Initial release
62 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2013-2014 Phusion
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | NAME = phusion/baseimage
2 | VERSION = 0.9.8
3 |
4 | .PHONY: all build test tag_latest release ssh
5 |
6 | all: build
7 |
8 | build:
9 | docker build -t $(NAME):$(VERSION) -rm image
10 |
11 | test:
12 | env NAME=$(NAME) VERSION=$(VERSION) ./test/runner.sh
13 |
14 | tag_latest:
15 | docker tag $(NAME):$(VERSION) $(NAME):latest
16 |
17 | release: test tag_latest
18 | @if ! docker images $(NAME) | awk '{ print $$2 }' | grep -q -F $(VERSION); then echo "$(NAME) version $(VERSION) is not yet built. Please run 'make build'"; false; fi
19 | docker push $(NAME)
20 | @echo "*** Don't forget to create a tag. git tag rel-$(VERSION) && git push origin rel-$(VERSION)"
21 |
22 | ssh:
23 | chmod 600 image/insecure_key.pub
24 | @ID=$$(docker ps | grep -F "$(NAME):$(VERSION)" | awk '{ print $$1 }') && \
25 | if test "$$ID" = ""; then echo "Container is not running."; exit 1; fi && \
26 | IP=$$(docker inspect $$ID | grep IPAddr | sed 's/.*: "//; s/".*//') && \
27 | echo "SSHing into $$IP" && \
28 | ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i image/insecure_key root@$$IP
29 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A minimal Ubuntu base image modified for Docker-friendliness
2 |
3 | Baseimage-docker is a special [Docker](http://www.docker.io) image that is configured for correct use within Docker containers. It is Ubuntu, plus modifications for Docker-friendliness. You can use it as a base for your own Docker images.
4 |
5 | Baseimage-docker is available for pulling from [the Docker registry](https://index.docker.io/u/phusion/baseimage/)!
6 |
7 | ### What are the problems with the stock Ubuntu base image?
8 |
9 | Ubuntu is not designed to be run inside docker. Its init system, Upstart, assumes that it's running on either real hardware or virtualized hardware, but not inside a Docker container. But inside a container you don't want a full system anyway, you want a minimal system. But configuring that minimal system for use within a container has many strange corner cases that are hard to get right if you are not intimately familiar with the Unix system model. This can cause a lot of strange problems.
10 |
11 | Baseimage-docker gets everything right. The "Contents" section describes all the things that it modifies.
12 |
13 |
14 | ### Why use baseimage-docker?
15 |
16 | You can configure the stock `ubuntu` image yourself from your Dockerfile, so why bother using baseimage-docker?
17 |
18 | * Configuring the base system for Docker-friendliness is no easy task. As stated before, there are many corner cases. By the time that you've gotten all that right, you've reinvented baseimage-docker. Using baseimage-docker will save you from this effort.
19 | * It reduces the time needed to write a correct Dockerfile. You won't have to worry about the base system and can focus on your stack and your app.
20 | * It reduces the time needed to run `docker build`, allowing you to iterate your Dockerfile more quickly.
21 | * It reduces download time during redeploys. Docker only needs to download the base image once: during the first deploy. On every subsequent deploys, only the changes you make on top of the base image are downloaded.
22 |
23 | -----------------------------------------
24 |
25 | **Related resources**:
26 | [Website](http://phusion.github.io/baseimage-docker/) |
27 | [Github](https://github.com/phusion/baseimage-docker) |
28 | [Docker registry](https://index.docker.io/u/phusion/baseimage/) |
29 | [Discussion forum](https://groups.google.com/d/forum/passenger-docker) |
30 | [Twitter](https://twitter.com/phusion_nl) |
31 | [Blog](http://blog.phusion.nl/)
32 |
33 | **Table of contents**
34 |
35 | * [What's inside the image?](#whats_inside)
36 | * [Overview](#whats_inside_overview)
37 | * [Wait, I thought Docker is about running a single process in a container?](#docker_single_process)
38 | * [Inspecting baseimage-docker](#inspecting)
39 | * [Using baseimage-docker as base image](#using)
40 | * [Getting started](#getting_started)
41 | * [Adding additional daemons](#adding_additional_daemons)
42 | * [Running scripts during container startup](#running_startup_scripts)
43 | * [Running a one-shot command in the container](#oneshot)
44 | * [Environment variables](#environment_variables)
45 | * [Centrally defining your own environment variables](#envvar_central_definition)
46 | * [Environment variable dumps](#envvar_dumps)
47 | * [Modifying environment variables](#modifying_envvars)
48 | * [Security](#envvar_security)
49 | * [Login to the container via SSH](#login)
50 | * [Using the insecure key for one container only](#using_the_insecure_key_for_one_container_only)
51 | * [Enabling the insecure key permanently](#enabling_the_insecure_key_permanently)
52 | * [Using your own key](#using_your_own_key)
53 | * [Disabling SSH](#disabling_ssh)
54 | * [Building the image yourself](#building)
55 | * [Conclusion](#conclusion)
56 |
57 | -----------------------------------------
58 |
59 |
60 | ## What's inside the image?
61 |
62 |
63 | ### Overview
64 |
65 | *Looking for a more complete base image, one that is ideal for Ruby, Python, Node.js and Meteor web apps? Take a look at [passenger-docker](https://github.com/phusion/passenger-docker).*
66 |
67 | | Component | Why is it included? / Remarks |
68 | | ---------------- | ------------------- |
69 | | Ubuntu 12.04 LTS | The base system. |
70 | | A **correct** init process | According to the Unix process model, [the init process](https://en.wikipedia.org/wiki/Init) -- PID 1 -- inherits all [orphaned child processes](https://en.wikipedia.org/wiki/Orphan_process) and must [reap them](https://en.wikipedia.org/wiki/Wait_(system_call)). Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with [zombie processes](https://en.wikipedia.org/wiki/Zombie_process) over time.
Furthermore, `docker stop` sends SIGTERM to the init process, which is then supposed to stop all services. Unfortunately most init systems don't do this correctly within Docker since they're built for hardware shutdowns instead. This causes processes to be hard killed with SIGKILL, which doesn't give them a chance to correctly deinitialize things. This can cause file corruption.
Baseimage-docker comes with an init process `/sbin/my_init` that performs both of these tasks correctly. |
71 | | Fixes APT incompatibilities with Docker | See https://github.com/dotcloud/docker/issues/1024. |
72 | | syslog-ng | A syslog daemon is necessary so that many services - including the kernel itself - can correctly log to /var/log/syslog. If no syslog daemon is running, a lot of important messages are silently swallowed.
Only listens locally. |
73 | | logrotate | Rotates and compresses logs on a regular basis. |
74 | | ssh server | Allows you to easily login to your container to inspect or administer things.
Password and challenge-response authentication are disabled by default. Only key authentication is allowed.
SSH access can be easily disabled if you so wish. Read on for instructions. |
75 | | cron | The cron daemon must be running for cron jobs to work. |
76 | | [runit](http://smarden.org/runit/) | Replaces Ubuntu's Upstart. Used for service supervision and management. Much easier to use than SysV init and supports restarting daemons when they crash. Much easier to use and more lightweight than Upstart. |
77 | | `setuser` | A tool for running a command as another user. Easier to use than `su`, has a smaller attack vector than `sudo`, and unlike `chpst` this tool sets `$HOME` correctly. Available as `/sbin/setuser`. |
78 |
79 | Baseimage-docker is very lightweight: it only consumes 6 MB of memory.
80 |
81 |
82 | ### Wait, I thought Docker is about running a single process in a container?
83 |
84 | Absolutely not true. Docker runs fine with multiple processes in a container. In fact, there is no technical reason why you should limit yourself to one process - it only makes things harder for you and breaks all kinds of essential system functionality, e.g. syslog.
85 |
86 | Baseimage-docker *encourages* multiple processes through the use of runit.
87 |
88 |
89 | ## Inspecting baseimage-docker
90 |
91 | To look around in the image, run:
92 |
93 | docker run -rm -t -i phusion/baseimage /sbin/my_init -- bash -l
94 |
95 | You don't have to download anything manually. The above command will automatically pull the baseimage-docker image from the Docker registry.
96 |
97 |
98 | ## Using baseimage-docker as base image
99 |
100 |
101 | ### Getting started
102 |
103 | The image is called `phusion/baseimage`, and is available on the Docker registry.
104 |
105 | # Use phusion/baseimage as base image. To make your builds reproducible, make
106 | # sure you lock down to a specific version, not to `latest`!
107 | # See https://github.com/phusion/baseimage-docker/blob/master/Changelog.md for
108 | # a list of version numbers.
109 | FROM phusion/baseimage:
110 |
111 | # Set correct environment variables.
112 | ENV HOME /root
113 |
114 | # Regenerate SSH host keys. baseimage-docker does not contain any, so you
115 | # have to do that yourself. You may also comment out this instruction; the
116 | # init system will auto-generate one during boot.
117 | RUN /etc/my_init.d/00_regen_ssh_host_keys.sh
118 |
119 | # Use baseimage-docker's init system.
120 | CMD ["/sbin/my_init"]
121 |
122 | # ...put your own build instructions here...
123 |
124 | # Clean up APT when done.
125 | RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
126 |
127 |
128 | ### Adding additional daemons
129 |
130 | You can add additional daemons (e.g. your own app) to the image by creating runit entries. You only have to write a small shell script which runs your daemon, and runit will keep it up and running for you, restarting it when it crashes, etc.
131 |
132 | The shell script must be called `run`, must be executable, and is to be placed in the directory `/etc/service/`.
133 |
134 | Here's an example showing you how a memached server runit entry can be made.
135 |
136 | ### In memcached.sh (make sure this file is chmod +x):
137 | #!/bin/sh
138 | # `/sbin/setuser memcache` runs the given command as the user `memcache`.
139 | # If you omit that part, the command will be run as root.
140 | exec /sbin/setuser memcache /usr/bin/memcached >>/var/log/memcached.log 2>&1
141 |
142 | ### In Dockerfile:
143 | RUN mkdir /etc/service/memcached
144 | ADD memcached.sh /etc/service/memcached/run
145 |
146 | Note that the shell script must run the daemon **without letting it daemonize/fork it**. Usually, daemons provide a command line flag or a config file option for that.
147 |
148 |
149 | ### Running scripts during container startup
150 |
151 | The baseimage-docker init system, `/sbin/my_init`, runs the following scripts during startup, in the following order:
152 |
153 | * All executable scripts in `/etc/my_init.d`, if this directory exists. The scripts are run during in lexicographic order.
154 | * The script `/etc/rc.local`, if this file exists.
155 |
156 | All scripts must exit correctly, e.g. with exit code 0. If any script exits with a non-zero exit code, the booting will fail.
157 |
158 | The following example shows how you can add a startup script. This script simply logs the time of boot to the file /tmp/boottime.txt.
159 |
160 | ### In logtime.sh (make sure this file is chmod +x):
161 | #!/bin/sh
162 | date > /tmp/boottime.txt
163 |
164 | ### In Dockerfile:
165 | RUN mkdir -p /etc/my_init.d
166 | ADD logtime.sh /etc/my_init.d/logtime.sh
167 |
168 |
169 | ### Running a one-shot command in the container
170 |
171 | Normally, when you want to run a single command in a container, and exit immediately after the command, you invoke Docker like this:
172 |
173 | docker run YOUR_IMAGE COMMAND ARGUMENTS...
174 |
175 | However the downside of this approach is that the init system is not started. That is, while invoking `COMMAND`, important daemons such as cron and syslog are not running. Also, orphaned child processes are not properly reaped, because `COMMAND` is PID 1.
176 |
177 | Baseimage-docker provides a facility to run a single one-shot command, while solving all of the aforementioned problems. Run a single command in the following manner:
178 |
179 | docker run YOUR_IMAGE /sbin/my_init -- COMMAND ARGUMENTS ...
180 |
181 | This will perform the following:
182 |
183 | * Runs all system startup files, such as /etc/my_init.d/* and /etc/rc.local.
184 | * Starts all runit services.
185 | * Runs the specified command.
186 | * When the specified command exits, stops all runit services.
187 |
188 | For example:
189 |
190 | $ docker run phusion/baseimage: /sbin/my_init -- ls
191 | *** Running /etc/my_init.d/00_regen_ssh_host_keys.sh...
192 | No SSH host key available. Generating one...
193 | Creating SSH2 RSA key; this may take some time ...
194 | Creating SSH2 DSA key; this may take some time ...
195 | Creating SSH2 ECDSA key; this may take some time ...
196 | *** Running /etc/rc.local...
197 | *** Booting runit daemon...
198 | *** Runit started as PID 80
199 | *** Running ls...
200 | bin boot dev etc home image lib lib64 media mnt opt proc root run sbin selinux srv sys tmp usr var
201 | *** ls exited with exit code 0.
202 | *** Shutting down runit daemon (PID 80)...
203 | *** Killing all processes...
204 |
205 | You may find that the default invocation is too noisy. Or perhaps you don't want to run the startup files. You can customize all this by passing arguments to `my_init`. Invoke `docker run YOUR_IMAGE /sbin/my_init --help` for more information.
206 |
207 | The following example runs `ls` without running the startup files and with less messages, while running all runit services:
208 |
209 | $ docker run phusion/baseimage: /sbin/my_init --skip-startup-files --quiet -- ls
210 | bin boot dev etc home image lib lib64 media mnt opt proc root run sbin selinux srv sys tmp usr var
211 |
212 |
213 | ### Environment variables
214 |
215 | If you use `/sbin/my_init` as the main container command, then any environment variables set with `docker run --env` or with the `ENV` command in the Dockerfile, will be picked up by `my_init`. These variables will also be passed to all child processes, including `/etc/my_init.d` startup scripts, Runit and Runit-managed services. There are however a few caveats you should be aware of:
216 |
217 | * Environment variables on Unix are inherited on a per-process basis. This means that it is generally not possible for a child process to change the environment variables of other processes.
218 | * Because of the aforementioned point, there is no good central place for defining environment variables for all applications and services. Debian has the `/etc/environment` file but it only works in some situations.
219 | * Some services change environment variables for child processes. Nginx is one such example: it removes all environment variables unless you explicitly instruct it to retain them through the `env` configuration option. If you host any applications on Nginx (e.g. using the [passenger-docker](https://github.com/phusion/passenger-docker) image, or using Phusion Passenger in your own image) then they will not see the environment variables that were originally passed by Docker.
220 |
221 | `my_init` provides a solution for all these caveats.
222 |
223 |
224 | #### Centrally defining your own environment variables
225 |
226 | During startup, before running any [startup scripts](#running_startup_scripts), `my_init` imports environment variables from the directory `/etc/container_environment`. This directory contains files who are named after the environment variable names. The file contents contain the environment variable values. This directory is therefore a good place to centrally define your own environment variables, which will be inherited by all startup scripts and Runit services.
227 |
228 | For example, here's how you can define an environment variable from your Dockerfile:
229 |
230 | RUN echo -n Apachai Hopachai > /etc/container_environment/MY_NAME
231 |
232 | You can verify that it works, as follows:
233 |
234 | $ docker run -t -i /sbin/my_init -- bash -l
235 | ...
236 | *** Running bash -l...
237 | # echo $MY_NAME
238 | Apachai Hopachai
239 |
240 |
241 | #### Environment variable dumps
242 |
243 | While the previously mentioned mechanism is good for centrally defining environment variables, it by itself does not prevent services (e.g. Nginx) from changing and resetting environment variables from child processes. However, the `my_init` mechanism does make it easy for you to query what the original environment variables are.
244 |
245 | During startup, right after importing environment variables from `/etc/container_environment`, `my_init` will dump all its environment variables (that is, all variables imported from `container_environment`, as well as all variables it picked up from `docker run --env`) to the following locations, in the following formats:
246 |
247 | * `/etc/container_environment`
248 | * `/etc/container_environment.sh` - a dump of the environment variables in Bash format. You can source the file directly from a Bash shell script.
249 | * `/etc/container_environment.json` - a dump of the environment variables in JSON format.
250 |
251 | The multiple formats makes it easy for you to query the original environment variables no matter which language your scripts/apps are written in.
252 |
253 | Here is an example shell session showing you how the dumps look like:
254 |
255 | $ docker run -t -i \
256 | --env FOO=bar --env HELLO='my beautiful world' \
257 | phusion/baseimage: /sbin/my_init -- \
258 | bash -l
259 | ...
260 | *** Running bash -l...
261 | # ls /etc/container_environment
262 | FOO HELLO HOME HOSTNAME PATH TERM container
263 | # cat /etc/container_environment/HELLO; echo
264 | my beautiful world
265 | # cat /etc/container_environment.json; echo
266 | {"TERM": "xterm", "container": "lxc", "HOSTNAME": "f45449f06950", "HOME": "/root", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "FOO": "bar", "HELLO": "my beautiful world"}
267 | # source /etc/container_environment.sh
268 | # echo $HELLO
269 | my beautiful world
270 |
271 |
272 | #### Modifying environment variables
273 |
274 | It is even possible to modify the environment variables in `my_init` (and therefore the environment variables in all child processes that are spawned after that point in time), by altering the files in `/etc/container_environment`. After each time `my_init` runs a [startup script](#running_startup_scripts), it resets its own environment variables to the state in `/etc/container_environment`, and re-dumps the new environment variables to `container_environment.sh` and `container_environment.json`.
275 |
276 | But note that:
277 |
278 | * modifying `container_environment.sh` and `container_environment.json` has no effect.
279 | * Runit services cannot modify the environment like that. `my_init` only activates changes in `/etc/container_environment` when running startup scripts.
280 |
281 |
282 | #### Security
283 |
284 | Because environment variables can potentially contain sensitive information, `/etc/container_environment` and its Bash and JSON dumps are by default owned by root, and root-accessible only. If you are sure that your environment variables don't contain sensitive data, then you can relax the permissions on that directory and those files by making them world-readable:
285 |
286 | RUN chmod 755 /etc/container_environment
287 | RUN chmod 644 /etc/container_environment.sh /etc/container_environment.json
288 |
289 |
290 | ### Login to the container via SSH
291 |
292 | You can use SSH to login to any container that is based on baseimage-docker.
293 |
294 | The first thing that you need to do is to ensure that you have the right SSH keys installed inside the container. By default, no keys are installed, so you can't login. For convenience reasons, we provide [a pregenerated, insecure key](https://github.com/phusion/baseimage-docker/blob/master/image/insecure_key) [(PuTTY format)](https://github.com/phusion/baseimage-docker/blob/master/image/insecure_key.ppk) that you can easily enable. However, please be aware that using this key is for convenience only. It does not provide any security because this key (both the public and the private side) is publicly available. **In production environments, you should use your own keys**.
295 |
296 |
297 | #### Using the insecure key for one container only
298 |
299 | You can temporarily enable the insecure key for one container only. This means that the insecure key is installed at container boot. If you `docker stop` and `docker start` the container, the insecure key will still be there, but if you use `docker run` to start a new container then that container will not contain the insecure key.
300 |
301 | Start a container with `--enable-insecure-key`:
302 |
303 | docker run YOUR_IMAGE /sbin/my_init --enable-insecure-key
304 |
305 | Find out the ID of the container that you just ran:
306 |
307 | docker ps
308 |
309 | Once you have the ID, look for its IP address with:
310 |
311 | docker inspect | grep IPAddress
312 |
313 | Now SSH into the container as follows:
314 |
315 | curl -o insecure_key -fSL https://github.com/phusion/baseimage-docker/raw/master/image/insecure_key
316 | chmod 600 insecure_key
317 | ssh -i insecure_key root@
318 |
319 |
320 | #### Enabling the insecure key permanently
321 |
322 | It is also possible to enable the insecure key in the image permanently. This is not generally recommended, but it suitable for e.g. temporary development or demo environments where security does not matter.
323 |
324 | Edit your Dockerfile to install the insecure key permanently:
325 |
326 | RUN /usr/sbin/enable_insecure_key
327 |
328 | Instructions for logging in the container is the same as in section [Using the insecure key for one container only](#using_the_insecure_key_for_one_container_only).
329 |
330 |
331 | #### Using your own key
332 |
333 | Edit your Dockerfile to install an SSH key:
334 |
335 | ## Install an SSH of your choice.
336 | ADD your_key /tmp/your_key
337 | RUN cat /tmp/your_key >> /root/.ssh/authorized_keys && rm -f /tmp/your_key
338 |
339 | Then rebuild your image. Once you have that, start a container based on that image:
340 |
341 | docker run your-image-name
342 |
343 | Find out the ID of the container that you just ran:
344 |
345 | docker ps
346 |
347 | Once you have the ID, look for its IP address with:
348 |
349 | docker inspect | grep IPAddress
350 |
351 | Now SSH into the container as follows:
352 |
353 | ssh -i /path-to/your_key root@
354 |
355 |
356 |
357 | ## Building the image yourself
358 |
359 | If for whatever reason you want to build the image yourself instead of downloading it from the Docker registry, follow these instructions.
360 |
361 | Clone this repository:
362 |
363 | git clone https://github.com/phusion/baseimage-docker.git
364 | cd baseimage-docker
365 |
366 | Start a virtual machine with Docker in it. You can use the Vagrantfile that we've already provided.
367 |
368 | vagrant up
369 | vagrant ssh
370 | cd /vagrant
371 |
372 | Build the image:
373 |
374 | make build
375 |
376 | If you want to call the resulting image something else, pass the NAME variable, like this:
377 |
378 | make build NAME=joe/baseimage
379 |
380 |
381 | ### Disabling SSH
382 |
383 | In case you do not want to enable SSH, here's how you can disable it:
384 |
385 | RUN rm -rf /etc/service/sshd /etc/my_init.d/00_regen_ssh_host_keys.sh
386 |
387 |
388 | ## Conclusion
389 |
390 | * Using baseimage-docker? [Tweet about us](https://twitter.com/share) or [follow us on Twitter](https://twitter.com/phusion_nl).
391 | * Having problems? Want to participate in development? Please post a message at [the discussion forum](https://groups.google.com/d/forum/passenger-docker).
392 | * Looking for a more complete base image, one that is ideal for Ruby, Python, Node.js and Meteor web apps? Take a look at [passenger-docker](https://github.com/phusion/passenger-docker).
393 |
394 | [
](http://www.phusion.nl/)
395 |
396 | Please enjoy baseimage-docker, a product by [Phusion](http://www.phusion.nl/). :-)
397 |
--------------------------------------------------------------------------------
/Vagrantfile:
--------------------------------------------------------------------------------
1 | # -*- mode: ruby -*-
2 | # vi: set ft=ruby :
3 | ROOT = File.dirname(File.expand_path(__FILE__))
4 |
5 | # Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
6 | VAGRANTFILE_API_VERSION = "2"
7 |
8 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
9 | config.vm.box = "phusion-open-ubuntu-12.04-amd64"
10 | config.vm.box_url = "https://oss-binaries.phusionpassenger.com/vagrant/boxes/ubuntu-12.04.3-amd64-vbox.box"
11 | config.ssh.forward_agent = true
12 | if File.directory?("#{ROOT}/../passenger-docker")
13 | config.vm.synced_folder File.expand_path("#{ROOT}/../passenger-docker"),
14 | "/vagrant/passenger-docker"
15 | end
16 |
17 | config.vm.provider :vmware_fusion do |f, override|
18 | override.vm.box_url = "https://oss-binaries.phusionpassenger.com/vagrant/boxes/ubuntu-12.04.3-amd64-vmwarefusion.box"
19 | f.vmx["displayName"] = "baseimage-docker"
20 | end
21 |
22 | if Dir.glob("#{File.dirname(__FILE__)}/.vagrant/machines/default/*/id").empty?
23 | # Add lxc-docker package
24 | pkg_cmd = "wget -q -O - https://get.docker.io/gpg | apt-key add -;" \
25 | "echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list;" \
26 | "apt-get update -qq; apt-get install -q -y --force-yes lxc-docker; "
27 | # Add vagrant user to the docker group
28 | pkg_cmd << "usermod -a -G docker vagrant; "
29 | config.vm.provision :shell, :inline => pkg_cmd
30 | end
31 | end
32 |
--------------------------------------------------------------------------------
/image/00_regen_ssh_host_keys.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 | if [[ ! -e /etc/ssh/ssh_host_rsa_key ]]; then
4 | echo "No SSH host key available. Generating one..."
5 | export LC_ALL=C
6 | export DEBIAN_FRONTEND=noninteractive
7 | dpkg-reconfigure openssh-server
8 | fi
9 |
--------------------------------------------------------------------------------
/image/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:12.04
2 | MAINTAINER Phusion
3 |
4 | ENV HOME /root
5 | RUN mkdir /build
6 | ADD . /build
7 |
8 | RUN /build/prepare.sh && \
9 | /build/system_services.sh && \
10 | /build/utilities.sh && \
11 | /build/cleanup.sh
12 |
13 | CMD ["/sbin/my_init"]
14 |
--------------------------------------------------------------------------------
/image/buildconfig:
--------------------------------------------------------------------------------
1 | export LC_ALL=C
2 | export DEBIAN_FRONTEND=noninteractive
3 | minimal_apt_get_install='apt-get install -y --no-install-recommends'
4 |
--------------------------------------------------------------------------------
/image/cleanup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 | source /build/buildconfig
4 | set -x
5 |
6 | apt-get clean
7 | rm -rf /build
8 | rm -rf /tmp/* /var/tmp/*
9 |
10 | rm -f /etc/ssh/ssh_host_*
11 |
--------------------------------------------------------------------------------
/image/config/sshd_config:
--------------------------------------------------------------------------------
1 | # $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $
2 |
3 | # This is the sshd server system-wide configuration file. See
4 | # sshd_config(5) for more information.
5 |
6 | # This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin
7 |
8 | # The strategy used for options in the default sshd_config shipped with
9 | # OpenSSH is to specify options with their default value where
10 | # possible, but leave them commented. Uncommented options change a
11 | # default value.
12 |
13 | UseDNS no
14 |
15 | #Port 22
16 | #AddressFamily any
17 | #ListenAddress 0.0.0.0
18 | #ListenAddress ::
19 |
20 | # Disable legacy (protocol version 1) support in the server for new
21 | # installations. In future the default will change to require explicit
22 | # activation of protocol 1
23 | Protocol 2
24 |
25 | # HostKey for protocol version 1
26 | #HostKey /etc/ssh_host_key
27 | # HostKeys for protocol version 2
28 | #HostKey /etc/ssh_host_rsa_key
29 | #HostKey /etc/ssh_host_dsa_key
30 |
31 | # Lifetime and size of ephemeral version 1 server key
32 | #KeyRegenerationInterval 1h
33 | #ServerKeyBits 1024
34 |
35 | # Logging
36 | # obsoletes QuietMode and FascistLogging
37 | SyslogFacility AUTHPRIV
38 | #LogLevel INFO
39 |
40 | # Authentication:
41 |
42 | #LoginGraceTime 2m
43 | #PermitRootLogin yes
44 | #StrictModes yes
45 | #MaxAuthTries 6
46 | #MaxSessions 10
47 |
48 | #RSAAuthentication yes
49 | #PubkeyAuthentication yes
50 | #AuthorizedKeysFile .ssh/authorized_keys
51 |
52 | # For this to work you will also need host keys in /etc/ssh_known_hosts
53 | #RhostsRSAAuthentication no
54 | # similar for protocol version 2
55 | #HostbasedAuthentication no
56 | # Change to yes if you don't trust ~/.ssh/known_hosts for
57 | # RhostsRSAAuthentication and HostbasedAuthentication
58 | #IgnoreUserKnownHosts no
59 | # Don't read the user's ~/.rhosts and ~/.shosts files
60 | #IgnoreRhosts yes
61 |
62 | # To disable tunneled clear text passwords, change to no here! Also,
63 | # remember to set the UsePAM setting to 'no'.
64 | #PasswordAuthentication no
65 | #PermitEmptyPasswords no
66 |
67 | # SACL options
68 | # The default for the SACLSupport option is now "no", as this option has been
69 | # depreciated in favor of SACL enforcement in the PAM configuration (/etc/pam.d/sshd).
70 | #SACLSupport no
71 |
72 | # Change to no to disable s/key passwords
73 | # Disabled for passenger-docker. We only allow key authentication.
74 | ChallengeResponseAuthentication no
75 |
76 | # Kerberos options
77 | #KerberosAuthentication no
78 | #KerberosOrLocalPasswd yes
79 | #KerberosTicketCleanup yes
80 |
81 | # GSSAPI options
82 | #GSSAPIAuthentication no
83 | #GSSAPICleanupCredentials yes
84 | #GSSAPIStrictAcceptorCheck yes
85 | #GSSAPIKeyExchange no
86 |
87 | # Set this to 'yes' to enable PAM authentication, account processing,
88 | # and session processing. If this is enabled, PAM authentication will
89 | # be allowed through the ChallengeResponseAuthentication and
90 | # PasswordAuthentication. Depending on your PAM configuration,
91 | # PAM authentication via ChallengeResponseAuthentication may bypass
92 | # the setting of "PermitRootLogin without-password".
93 | # If you just want the PAM account and session checks to run without
94 | # PAM authentication, then enable this but set PasswordAuthentication
95 | # and ChallengeResponseAuthentication to 'no'.
96 | # Also, PAM will deny null passwords by default. If you need to allow
97 | # null passwords, add the " nullok" option to the end of the
98 | # securityserver.so line in /etc/pam.d/sshd.
99 | #UsePAM yes
100 |
101 | #AllowAgentForwarding yes
102 | #AllowTcpForwarding yes
103 | #GatewayPorts no
104 | #X11Forwarding no
105 | #X11DisplayOffset 10
106 | #X11UseLocalhost yes
107 | #PrintMotd yes
108 | #PrintLastLog yes
109 | #TCPKeepAlive yes
110 | #UseLogin no
111 | #UsePrivilegeSeparation yes
112 | #PermitUserEnvironment no
113 | #Compression delayed
114 | #ClientAliveInterval 0
115 | #ClientAliveCountMax 3
116 | #UseDNS yes
117 | #PidFile /var/run/sshd.pid
118 | #MaxStartups 10
119 | #PermitTunnel no
120 | #ChrootDirectory none
121 |
122 | # no default banner path
123 | #Banner none
124 |
125 | # override default of no subsystems
126 | Subsystem sftp /usr/lib/openssh/sftp-server
127 |
128 | # Example of overriding settings on a per-user basis
129 | #Match User anoncvs
130 | # X11Forwarding no
131 | # AllowTcpForwarding no
132 | # ForceCommand cvs server
133 |
134 | # XAuthLocation added by XQuartz (http://xquartz.macosforge.org)
135 | XAuthLocation /opt/X11/bin/xauth
136 |
--------------------------------------------------------------------------------
/image/config/syslog_ng_default:
--------------------------------------------------------------------------------
1 | # If a variable is not set here, then the corresponding
2 | # parameter will not be changed.
3 | # If a variables is set, then every invocation of
4 | # syslog-ng's init script will set them using dmesg.
5 |
6 | # log level of messages which should go to console
7 | # see syslog(3) for details
8 | #
9 | #CONSOLE_LOG_LEVEL=1
10 |
11 | # Command line options to syslog-ng
12 | # We set --default-modules because of https://github.com/phusion/baseimage-docker/pull/7.
13 | SYSLOGNG_OPTS="--no-caps --default-modules=affile,afprog,afsocket,afuser,basicfuncs,csvparser,dbparser,syslogformat"
14 |
--------------------------------------------------------------------------------
/image/enable_insecure_key:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | AUTHORIZED_KEYS=/root/.ssh/authorized_keys
5 |
6 | if [[ -e "$AUTHORIZED_KEYS" ]] && grep -q baseimage-docker-insecure-key "$AUTHORIZED_KEYS"; then
7 | echo "Insecure key has already been added to $AUTHORIZED_KEYS."
8 | else
9 | DIR=`dirname "$AUTHORIZED_KEYS"`
10 | echo "Creating directory $DIR..."
11 | mkdir -p "$DIR"
12 | chmod 700 "$DIR"
13 | chown root:root "$DIR"
14 | echo "Editing $AUTHORIZED_KEYS..."
15 | cat /etc/insecure_key.pub >> "$AUTHORIZED_KEYS"
16 | echo "Success: insecure key has been added to $AUTHORIZED_KEYS"
17 | cat <<-EOF
18 |
19 | +------------------------------------------------------------------------------+
20 | | Insecure SSH key installed |
21 | | |
22 | | DO NOT expose port 22 on the Internet unless you know what you are doing! |
23 | | |
24 | | Use the private key below to connect with user root |
25 | +------------------------------------------------------------------------------+
26 |
27 | EOF
28 | cat /etc/insecure_key
29 | echo -e "\n\n"
30 | fi
31 |
--------------------------------------------------------------------------------
/image/insecure_key:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEpQIBAAKCAQEA1ZswRub+3DvSEnBiyM5YRpRzRYV88vO1X2j867u6pyCHUNXv
3 | RRCr7ahMLPIVYsZwlHb4sF+Zb3DJOBH+E265o93chdMxbWG44k0spf10JRevA0JX
4 | NrEwHR8vesCR74e5MuddbSic88lsEqnnn+Fo3lStvE6nBp6tbqdEu7GhTtHSYejn
5 | wwINnA5ocsHkd1YE9L2Scqw1e4bXveTAQnSvhqe33QshGXFpt0tQwRWngah887f2
6 | P54wFSm2C/UyFT7pvIjINKzIi4vUoXz/nU+V7neTmt3XDdjloYg3ycOaX4RSVneO
7 | HCf7hkcEKbzbPzzSrGAAYYC5UzFB+ImsIbtV2wIDAQABAoIBAQCjROxgtX2Gft7y
8 | Ix8Ol9IXmK6HLCI2XZt7ovb3hFWGGzHy0qMBql2P2Tzoed1o038Hq+woe9n+uTnE
9 | dtQ6rD6PByzgyW2VSsWTjCOdeJ5HH9Qw7ItXDZZWHBkhfYHOkXI4e2oI3qshGAtY
10 | NLALn7KVhioJriCyyaSM2KOLx5khcY+EJ1inQfwQJKqPGsdKc72liz07T8ifRj+m
11 | NLKtwrxlK3IXYfIdgLp/1pCKdrC80DhprMsD4xvNgq4pCR9jd4FoqM9t/Up5ppTm
12 | +p6A/bDwdIPh6cFFeyMP+G3+bTlW1Gg7RLoNCc6qh53WWVgEOQqdLHcQ8Ge4RLmb
13 | wLUmnRuRAoGBAPfXYfjpPZi8rPIQpux13Bs7xaS1/Fa9WqrEfrPptFdUVHeFCGY8
14 | qOUVewPviHdbs0nB71Ynk9/e96agFYijQdqTQzVnpYI4i8GiGk5gPMiB2UYeJ/HZ
15 | mIB3jtWyf6Z/GO0hJ1a6mX0XD3zJGNqFaiwqaYgdO1Fwh9gcH3O2lHyjAoGBANyj
16 | TGDBYHpxPu6uKcGreLd0SgO61PEj7aOSNfrBB2PK83A+zjZCFZRIWqjfrkxGG6+a
17 | 2WuHbEHuCGvu2V5juHYxbAD/38iV/lQl/2xyvN1eR/baE3US06qn6idxjnmeNZDy
18 | DelAx1RGuEvLX1TNAzDTxBwYyzH3W2RpKAUAD11pAoGAN38YJhd8Pn5JL68A4cQG
19 | dGau/BHwHjAqZEC5qmmzgzaT72tvlQ0SOLHVqOzzHt7+x45QnHciSqfvxnTkPYNp
20 | FJuTGhtKWV12FfbJczFjivZgg63u/d3eoy2iY0GkCdE98KNS3r3L7tHCGwwgr5Xe
21 | T2Nz3BHHnZXYJVEuzcddeocCgYEAnhDjPAHtw2p0Inxlb9kPb6aBC/ECcwtBSUkL
22 | IOy/BZA1HPnxs89eNFAtmwQ8k2o6lXDDSJTJSuZj5CdGVKfuU8aOUJz/Tm2eudxL
23 | A/+jLJhJyCBthhcJyx3m04E4CAr+5ytyKeP9qXPMvoghcNg66/UabuKYV+CU+feX
24 | 8xUa7NkCgYEAlX8HGvWMmiG+ZRFB//3Loy87bBxGlN0pUtCEScabZxdB2HkI9Vp7
25 | Yr67QIZ3y7T88Mhkwam54JCjiV+3TZbSyRMOjkqf7UhTCZC6hHNqdUnlpv4bJWeW
26 | i5Eun8ltYxBnemNc2QGxA4r+KCspi+pRvWNGzL3PFVBGXiLsmOMul78=
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/image/insecure_key.ppk:
--------------------------------------------------------------------------------
1 | PuTTY-User-Key-File-2: ssh-rsa
2 | Encryption: none
3 | Comment: imported-openssh-key
4 | Public-Lines: 6
5 | AAAAB3NzaC1yc2EAAAADAQABAAABAQDVmzBG5v7cO9IScGLIzlhGlHNFhXzy87Vf
6 | aPzru7qnIIdQ1e9FEKvtqEws8hVixnCUdviwX5lvcMk4Ef4Tbrmj3dyF0zFtYbji
7 | TSyl/XQlF68DQlc2sTAdHy96wJHvh7ky511tKJzzyWwSqeef4WjeVK28TqcGnq1u
8 | p0S7saFO0dJh6OfDAg2cDmhyweR3VgT0vZJyrDV7hte95MBCdK+Gp7fdCyEZcWm3
9 | S1DBFaeBqHzzt/Y/njAVKbYL9TIVPum8iMg0rMiLi9ShfP+dT5Xud5Oa3dcN2OWh
10 | iDfJw5pfhFJWd44cJ/uGRwQpvNs/PNKsYABhgLlTMUH4iawhu1Xb
11 | Private-Lines: 14
12 | AAABAQCjROxgtX2Gft7yIx8Ol9IXmK6HLCI2XZt7ovb3hFWGGzHy0qMBql2P2Tzo
13 | ed1o038Hq+woe9n+uTnEdtQ6rD6PByzgyW2VSsWTjCOdeJ5HH9Qw7ItXDZZWHBkh
14 | fYHOkXI4e2oI3qshGAtYNLALn7KVhioJriCyyaSM2KOLx5khcY+EJ1inQfwQJKqP
15 | GsdKc72liz07T8ifRj+mNLKtwrxlK3IXYfIdgLp/1pCKdrC80DhprMsD4xvNgq4p
16 | CR9jd4FoqM9t/Up5ppTm+p6A/bDwdIPh6cFFeyMP+G3+bTlW1Gg7RLoNCc6qh53W
17 | WVgEOQqdLHcQ8Ge4RLmbwLUmnRuRAAAAgQD312H46T2YvKzyEKbsddwbO8WktfxW
18 | vVqqxH6z6bRXVFR3hQhmPKjlFXsD74h3W7NJwe9WJ5Pf3vemoBWIo0Hak0M1Z6WC
19 | OIvBohpOYDzIgdlGHifx2ZiAd47Vsn+mfxjtISdWupl9Fw98yRjahWosKmmIHTtR
20 | cIfYHB9ztpR8owAAAIEA3KNMYMFgenE+7q4pwat4t3RKA7rU8SPto5I1+sEHY8rz
21 | cD7ONkIVlEhaqN+uTEYbr5rZa4dsQe4Ia+7ZXmO4djFsAP/fyJX+VCX/bHK83V5H
22 | 9toTdRLTqqfqJ3GOeZ41kPIN6UDHVEa4S8tfVM0DMNPEHBjLMfdbZGkoBQAPXWkA
23 | AACBAJV/Bxr1jJohvmURQf/9y6MvO2wcRpTdKVLQhEnGm2cXQdh5CPVae2K+u0CG
24 | d8u0/PDIZMGpueCQo4lft02W0skTDo5Kn+1IUwmQuoRzanVJ5ab+GyVnlouRLp/J
25 | bWMQZ3pjXNkBsQOK/igrKYvqUb1jRsy9zxVQRl4i7JjjLpe/
26 | Private-MAC: ef1e472b5254ae2c5319a522d39ad31d432dde75
27 |
--------------------------------------------------------------------------------
/image/insecure_key.pub:
--------------------------------------------------------------------------------
1 | ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVmzBG5v7cO9IScGLIzlhGlHNFhXzy87VfaPzru7qnIIdQ1e9FEKvtqEws8hVixnCUdviwX5lvcMk4Ef4Tbrmj3dyF0zFtYbjiTSyl/XQlF68DQlc2sTAdHy96wJHvh7ky511tKJzzyWwSqeef4WjeVK28TqcGnq1up0S7saFO0dJh6OfDAg2cDmhyweR3VgT0vZJyrDV7hte95MBCdK+Gp7fdCyEZcWm3S1DBFaeBqHzzt/Y/njAVKbYL9TIVPum8iMg0rMiLi9ShfP+dT5Xud5Oa3dcN2OWhiDfJw5pfhFJWd44cJ/uGRwQpvNs/PNKsYABhgLlTMUH4iawhu1Xb baseimage-docker-insecure-key
2 |
--------------------------------------------------------------------------------
/image/my_init:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python2 -u
2 | import os, os.path, sys, stat, signal, errno, argparse, time, json, re, posixfile
3 |
4 | KILL_PROCESS_TIMEOUT = 5
5 | KILL_ALL_PROCESSES_TIMEOUT = 5
6 |
7 | LOG_LEVEL_ERROR = 1
8 | LOG_LEVEL_WARN = 1
9 | LOG_LEVEL_INFO = 2
10 | LOG_LEVEL_DEBUG = 3
11 |
12 | log_level = None
13 |
14 | class AlarmException(Exception):
15 | pass
16 |
17 | def error(message):
18 | if log_level >= LOG_LEVEL_ERROR:
19 | sys.stderr.write("*** %s\n" % message)
20 |
21 | def warn(message):
22 | if log_level >= LOG_LEVEL_WARN:
23 | print("*** %s" % message)
24 |
25 | def info(message):
26 | if log_level >= LOG_LEVEL_INFO:
27 | print("*** %s" % message)
28 |
29 | def debug(message):
30 | if log_level >= LOG_LEVEL_DEBUG:
31 | print("*** %s" % message)
32 |
33 | def ignore_signals_and_raise_keyboard_interrupt(signame):
34 | signal.signal(signal.SIGTERM, signal.SIG_IGN)
35 | signal.signal(signal.SIGINT, signal.SIG_IGN)
36 | raise KeyboardInterrupt(signame)
37 |
38 | def raise_alarm_exception():
39 | raise AlarmException('Alarm')
40 |
41 | def listdir(path):
42 | try:
43 | result = os.stat(path)
44 | except OSError:
45 | return []
46 | if stat.S_ISDIR(result.st_mode):
47 | return sorted(os.listdir(path))
48 | else:
49 | return []
50 |
51 | def is_exe(path):
52 | try:
53 | return os.path.isfile(path) and os.access(path, os.X_OK)
54 | except OSError:
55 | return False
56 |
57 | def import_envvars(clear_existing_environment = True):
58 | new_env = {}
59 | for envfile in listdir("/etc/container_environment"):
60 | name = os.path.basename(envfile)
61 | with open("/etc/container_environment/" + envfile, "r") as f:
62 | value = f.read()
63 | new_env[name] = value
64 | if clear_existing_environment:
65 | os.environ.clear()
66 | for name, value in new_env.items():
67 | os.environ[name] = value
68 |
69 | def export_envvars(to_dir = True):
70 | shell_dump = ""
71 | for name, value in os.environ.items():
72 | if to_dir:
73 | with open("/etc/container_environment/" + name, "w") as f:
74 | f.write(value)
75 | shell_dump += "export " + shquote(name) + "=" + shquote(value) + "\n"
76 | with open("/etc/container_environment.sh", "w") as f:
77 | f.write(shell_dump)
78 | with open("/etc/container_environment.json", "w") as f:
79 | f.write(json.dumps(dict(os.environ)))
80 |
81 | _find_unsafe = re.compile(r'[^\w@%+=:,./-]').search
82 |
83 | def shquote(s):
84 | """Return a shell-escaped version of the string *s*."""
85 | if not s:
86 | return "''"
87 | if _find_unsafe(s) is None:
88 | return s
89 |
90 | # use single quotes, and put single quotes into double quotes
91 | # the string $'b is then quoted as '$'"'"'b'
92 | return "'" + s.replace("'", "'\"'\"'") + "'"
93 |
94 | def waitpid_reap_other_children(pid):
95 | done = False
96 | status = None
97 | try:
98 | this_pid, status = os.waitpid(pid, os.WNOHANG)
99 | except OSError as e:
100 | if e.errno == errno.ECHILD or e.errno == errno.ESRCH:
101 | return None
102 | else:
103 | raise
104 | while not done:
105 | this_pid, status = os.waitpid(-1, 0)
106 | done = this_pid == pid
107 | return status
108 |
109 | def stop_child_process(name, pid, signo = signal.SIGTERM, time_limit = KILL_PROCESS_TIMEOUT):
110 | info("Shutting down %s (PID %d)..." % (name, pid))
111 | try:
112 | os.kill(pid, signo)
113 | except OSError:
114 | pass
115 | signal.alarm(time_limit)
116 | try:
117 | try:
118 | waitpid_reap_other_children(pid)
119 | except OSError:
120 | pass
121 | except AlarmException:
122 | warn("%s (PID %d) did not shut down in time. Forcing it to exit." % (name, pid))
123 | try:
124 | os.kill(pid, signal.SIGKILL)
125 | except OSError:
126 | pass
127 | try:
128 | waitpid_reap_other_children(pid)
129 | except OSError:
130 | pass
131 | finally:
132 | signal.alarm(0)
133 |
134 | def run_command_killable(*argv):
135 | filename = argv[0]
136 | status = None
137 | pid = os.spawnvp(os.P_NOWAIT, filename, argv)
138 | try:
139 | status = waitpid_reap_other_children(pid)
140 | except BaseException as s:
141 | warn("An error occurred. Aborting.")
142 | stop_child_process(filename, pid)
143 | raise
144 | if status != 0:
145 | if status is None:
146 | error("%s exited with unknown exit code\n" % filename)
147 | else:
148 | error("%s failed with exit code %d\n" % (filename, status))
149 | sys.exit(1)
150 |
151 | def run_command_killable_and_import_envvars(*argv):
152 | run_command_killable(*argv)
153 | import_envvars()
154 | export_envvars(False)
155 |
156 | def kill_all_processes(time_limit):
157 | info("Killing all processes...")
158 | try:
159 | os.kill(-1, signal.SIGTERM)
160 | except OSError:
161 | pass
162 | signal.alarm(time_limit)
163 | try:
164 | # Wait until no more child processes exist.
165 | done = False
166 | while not done:
167 | try:
168 | os.waitpid(-1, 0)
169 | except OSError as e:
170 | if e.errno == errno.ECHILD:
171 | done = True
172 | else:
173 | raise
174 | except AlarmException:
175 | warn("Not all processes have exited in time. Forcing them to exit.")
176 | try:
177 | os.kill(-1, signal.SIGKILL)
178 | except OSError:
179 | pass
180 | finally:
181 | signal.alarm(0)
182 |
183 | def run_startup_files():
184 | # Run /etc/my_init.d/*
185 | for name in listdir("/etc/my_init.d"):
186 | filename = "/etc/my_init.d/" + name
187 | if is_exe(filename):
188 | info("Running %s..." % filename)
189 | run_command_killable_and_import_envvars(filename)
190 |
191 | # Run /etc/rc.local.
192 | if is_exe("/etc/rc.local"):
193 | info("Running /etc/rc.local...")
194 | run_command_killable_and_import_envvars("/etc/rc.local")
195 |
196 | def start_runit():
197 | info("Booting runit daemon...")
198 | pid = os.spawnl(os.P_NOWAIT, "/usr/bin/runsvdir", "/usr/bin/runsvdir",
199 | "-P", "/etc/service", "log: %s" % ('.' * 395))
200 | info("Runit started as PID %d" % pid)
201 | return pid
202 |
203 | def wait_for_runit_or_interrupt(pid):
204 | try:
205 | status = waitpid_reap_other_children(pid)
206 | return (True, status)
207 | except KeyboardInterrupt:
208 | return (False, None)
209 |
210 | def shutdown_runit_services():
211 | debug("Begin shutting down runit services...")
212 | os.system("/usr/bin/sv down /etc/service/*")
213 |
214 | def wait_for_runit_services():
215 | debug("Waiting for runit services to exit...")
216 | done = False
217 | while not done:
218 | done = os.system("/usr/bin/sv status /etc/service/* | grep -q '^run:'") != 0
219 | if not done:
220 | time.sleep(0.1)
221 |
222 | def install_insecure_key():
223 | info("Installing insecure SSH key for user root")
224 | run_command_killable("/usr/sbin/enable_insecure_key")
225 |
226 | def main(args):
227 | import_envvars(False)
228 | export_envvars()
229 |
230 | if args.enable_insecure_key:
231 | install_insecure_key()
232 |
233 | if not args.skip_startup_files:
234 | run_startup_files()
235 |
236 | runit_exited = False
237 | exit_code = None
238 |
239 | if not args.skip_runit:
240 | runit_pid = start_runit()
241 | try:
242 | if len(args.main_command) == 0:
243 | runit_exited, exit_code = wait_for_runit_or_interrupt(runit_pid)
244 | if runit_exited:
245 | if exit_code is None:
246 | info("Runit exited with unknown exit code")
247 | exit_code = 1
248 | else:
249 | info("Runit exited with code %d" % exit_code)
250 | else:
251 | info("Running %s..." % " ".join(args.main_command))
252 | pid = os.spawnvp(os.P_NOWAIT, args.main_command[0], args.main_command)
253 | try:
254 | exit_code = waitpid_reap_other_children(pid)
255 | if exit_code is None:
256 | info("%s exited with unknown exit code." % args.main_command[0])
257 | exit_code = 1
258 | else:
259 | info("%s exited with exit code %d." % (args.main_command[0], exit_code))
260 | except KeyboardInterrupt:
261 | stop_child_process(args.main_command[0], pid)
262 | except BaseException as s:
263 | warn("An error occurred. Aborting.")
264 | stop_child_process(args.main_command[0], pid)
265 | raise
266 | sys.exit(exit_code)
267 | finally:
268 | if not args.skip_runit:
269 | shutdown_runit_services()
270 | if not runit_exited:
271 | stop_child_process("runit daemon", runit_pid)
272 | wait_for_runit_services()
273 |
274 | # Parse options.
275 | parser = argparse.ArgumentParser(description = 'Initialize the system.')
276 | parser.add_argument('main_command', metavar = 'MAIN_COMMAND', type = str, nargs = '*',
277 | help = 'The main command to run. (default: runit)')
278 | parser.add_argument('--enable-insecure-key', dest = 'enable_insecure_key',
279 | action = 'store_const', const = True, default = False,
280 | help = 'Install the insecure SSH key')
281 | parser.add_argument('--skip-startup-files', dest = 'skip_startup_files',
282 | action = 'store_const', const = True, default = False,
283 | help = 'Skip running /etc/my_init.d/* and /etc/rc.local')
284 | parser.add_argument('--skip-runit', dest = 'skip_runit',
285 | action = 'store_const', const = True, default = False,
286 | help = 'Do not run runit services')
287 | parser.add_argument('--no-kill-all-on-exit', dest = 'kill_all_on_exit',
288 | action = 'store_const', const = False, default = True,
289 | help = 'Don\'t kill all processes on the system upon exiting')
290 | parser.add_argument('--quiet', dest = 'log_level',
291 | action = 'store_const', const = LOG_LEVEL_WARN, default = LOG_LEVEL_INFO,
292 | help = 'Only print warnings and errors')
293 | args = parser.parse_args()
294 | log_level = args.log_level
295 |
296 | if args.skip_runit and len(args.main_command) == 0:
297 | error("When --skip-runit is given, you must also pass a main command.")
298 | sys.exit(1)
299 |
300 | # Run main function.
301 | signal.signal(signal.SIGTERM, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGTERM'))
302 | signal.signal(signal.SIGINT, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGINT'))
303 | signal.signal(signal.SIGALRM, lambda signum, frame: raise_alarm_exception())
304 | try:
305 | main(args)
306 | except KeyboardInterrupt:
307 | warn("Init system aborted.")
308 | exit(2)
309 | finally:
310 | if args.kill_all_on_exit:
311 | kill_all_processes(KILL_ALL_PROCESSES_TIMEOUT)
312 |
--------------------------------------------------------------------------------
/image/prepare.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 | source /build/buildconfig
4 | set -x
5 |
6 | ## Enable Ubuntu Universe.
7 | echo deb http://archive.ubuntu.com/ubuntu precise main universe > /etc/apt/sources.list
8 | echo deb http://archive.ubuntu.com/ubuntu precise-updates main universe >> /etc/apt/sources.list
9 | apt-get update
10 |
11 | ## Install HTTPS support for APT.
12 | $minimal_apt_get_install apt-transport-https
13 |
14 | ## Fix some issues with APT packages.
15 | ## See https://github.com/dotcloud/docker/issues/1024
16 | dpkg-divert --local --rename --add /sbin/initctl
17 | ln -sf /bin/true /sbin/initctl
18 |
19 | ## Upgrade all packages.
20 | echo "initscripts hold" | dpkg --set-selections
21 | apt-get upgrade -y --no-install-recommends
22 |
23 | ## Fix locale.
24 | $minimal_apt_get_install language-pack-en
25 | locale-gen en_US
26 |
--------------------------------------------------------------------------------
/image/runit/cron:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | exec /usr/sbin/cron -f
3 |
--------------------------------------------------------------------------------
/image/runit/sshd:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | set -e
3 | exec /usr/sbin/sshd -D
4 |
--------------------------------------------------------------------------------
/image/runit/syslog-ng:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | set -e
3 |
4 | SYSLOGNG_OPTS=""
5 |
6 | [ -r /etc/default/syslog-ng ] && . /etc/default/syslog-ng
7 |
8 | case "x$CONSOLE_LOG_LEVEL" in
9 | x[1-8])
10 | dmesg -n $CONSOLE_LOG_LEVEL
11 | ;;
12 | x)
13 | ;;
14 | *)
15 | echo "CONSOLE_LOG_LEVEL is of unaccepted value."
16 | ;;
17 | esac
18 |
19 | if [ ! -e /dev/xconsole ]
20 | then
21 | mknod -m 640 /dev/xconsole p
22 | fi
23 |
24 | exec syslog-ng -F -p /var/run/syslog-ng.pid $SYSLOGNG_OPTS
25 |
--------------------------------------------------------------------------------
/image/setuser:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python2
2 | import sys, os, pwd
3 |
4 | if len(sys.argv) < 3:
5 | sys.stderr.write("Usage: /sbin/setuser USERNAME COMMAND [args..]\n")
6 | sys.exit(1)
7 |
8 | def abort(message):
9 | sys.stderr.write("setuser: %s\n" % message)
10 | sys.exit(1)
11 |
12 | username = sys.argv[1]
13 | try:
14 | user = pwd.getpwnam(username)
15 | except KeyError:
16 | abort("user %s not found" % username)
17 | os.initgroups(username, user.pw_gid)
18 | os.setgid(user.pw_gid)
19 | os.setuid(user.pw_uid)
20 | os.environ['USER'] = username
21 | os.environ['HOME'] = user.pw_dir
22 | os.environ['UID'] = str(user.pw_uid)
23 | try:
24 | os.execvp(sys.argv[2], sys.argv[2:])
25 | except OSError as e:
26 | abort("cannot execute %s: %s" % (sys.argv[2], str(e)))
27 |
--------------------------------------------------------------------------------
/image/system_services.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 | source /build/buildconfig
4 | set -x
5 |
6 | ## Install init process.
7 | cp /build/my_init /sbin/
8 | mkdir -p /etc/my_init.d
9 | mkdir -p /etc/container_environment
10 | touch /etc/container_environment.sh
11 | touch /etc/container_environment.json
12 | chmod 700 /etc/container_environment
13 | chmod 600 /etc/container_environment.sh /etc/container_environment.json
14 |
15 | ## Install runit.
16 | $minimal_apt_get_install runit
17 |
18 | ## Install a syslog daemon.
19 | $minimal_apt_get_install syslog-ng-core
20 | mkdir /etc/service/syslog-ng
21 | cp /build/runit/syslog-ng /etc/service/syslog-ng/run
22 | mkdir -p /var/lib/syslog-ng
23 | cp /build/config/syslog_ng_default /etc/default/syslog-ng
24 |
25 | ## Install logrotate.
26 | $minimal_apt_get_install logrotate
27 |
28 | ## Install the SSH server.
29 | $minimal_apt_get_install openssh-server
30 | mkdir /var/run/sshd
31 | mkdir /etc/service/sshd
32 | cp /build/runit/sshd /etc/service/sshd/run
33 | cp /build/config/sshd_config /etc/ssh/sshd_config
34 | cp /build/00_regen_ssh_host_keys.sh /etc/my_init.d/
35 |
36 | ## Install default SSH key for root and app.
37 | mkdir -p /root/.ssh
38 | chmod 700 /root/.ssh
39 | chown root:root /root/.ssh
40 | cp /build/insecure_key.pub /etc/insecure_key.pub
41 | cp /build/insecure_key /etc/insecure_key
42 | chmod 644 /etc/insecure_key*
43 | chown root:root /etc/insecure_key*
44 | cp /build/enable_insecure_key /usr/sbin/
45 |
46 | ## Install cron daemon.
47 | $minimal_apt_get_install cron
48 | mkdir /etc/service/cron
49 | cp /build/runit/cron /etc/service/cron/run
50 |
51 | ## Remove useless cron entries.
52 | # Checks for lost+found and scans for mtab.
53 | rm -f /etc/cron.daily/standard
54 |
--------------------------------------------------------------------------------
/image/utilities.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 | source /build/buildconfig
4 | set -x
5 |
6 | ## Often used tools.
7 | $minimal_apt_get_install curl less nano vim psmisc
8 |
9 | ## This tool runs a command as another user and sets $HOME.
10 | cp /build/setuser /sbin/setuser
11 |
--------------------------------------------------------------------------------
/test/runner.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -e
3 |
4 | function abort()
5 | {
6 | echo "$@"
7 | exit 1
8 | }
9 |
10 | function cleanup()
11 | {
12 | echo " --> Stopping container"
13 | docker stop $ID >/dev/null
14 | docker rm $ID >/dev/null
15 | }
16 |
17 | PWD=`pwd`
18 |
19 | echo " --> Starting insecure container"
20 | ID=`docker run -d -v $PWD/test:/test $NAME:$VERSION /sbin/my_init --enable-insecure-key`
21 | sleep 1
22 |
23 | echo " --> Obtaining IP"
24 | IP=`docker inspect $ID | grep IPAddress | sed -e 's/.*: "//; s/".*//'`
25 | if [[ "$IP" = "" ]]; then
26 | abort "Unable to obtain container IP"
27 | fi
28 |
29 | trap cleanup EXIT
30 |
31 | echo " --> Logging into container and running tests"
32 | chmod 600 image/insecure_key
33 | sleep 1 # Give container some more time to start up.
34 | ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i image/insecure_key root@$IP \
35 | /bin/bash /test/test.sh
36 |
--------------------------------------------------------------------------------
/test/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -o pipefail
3 |
4 | function ok()
5 | {
6 | echo " OK"
7 | }
8 |
9 | function fail()
10 | {
11 | echo " FAIL"
12 | exit 1
13 | }
14 |
15 | echo "Checking whether all services are running..."
16 | services=`sv status /etc/service/*`
17 | status=$?
18 | if [[ "$status" != 0 || "$services" = "" || "$services" =~ down ]]; then
19 | fail
20 | else
21 | ok
22 | fi
23 |
--------------------------------------------------------------------------------