Initial commit

This commit is contained in:
Ria Bhatia
2017-12-04 13:32:57 -06:00
committed by Erik St. Martin
commit 0075e5b0f3
9056 changed files with 2523100 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
#
# Build: docker build -t apt-cacher .
# Run: docker run -d -p 3142:3142 --name apt-cacher-run apt-cacher
#
# and then you can run containers with:
# docker run -t -i --rm -e http_proxy http://dockerhost:3142/ debian bash
#
FROM ubuntu
MAINTAINER SvenDowideit@docker.com
VOLUME ["/var/cache/apt-cacher-ng"]
RUN apt-get update && apt-get install -y apt-cacher-ng
EXPOSE 3142
CMD chmod 777 /var/cache/apt-cacher-ng && /etc/init.d/apt-cacher-ng start && tail -f /var/log/apt-cacher-ng/*

View File

@@ -0,0 +1,126 @@
<!--[metadata]>
+++
title = "Dockerizing an apt-cacher-ng service"
description = "Installing and running an apt-cacher-ng service"
keywords = ["docker, example, package installation, networking, debian, ubuntu"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing an apt-cacher-ng service
> **Note**:
> - **If you don't like sudo** then see [*Giving non-root
> access*](../installation/binaries.md#giving-non-root-access).
> - **If you're using OS X or docker via TCP** then you shouldn't use
> sudo.
When you have multiple Docker servers, or build unrelated Docker
containers which can't make use of the Docker build cache, it can be
useful to have a caching proxy for your packages. This container makes
the second download of any package almost instant.
Use the following Dockerfile:
#
# Build: docker build -t apt-cacher .
# Run: docker run -d -p 3142:3142 --name apt-cacher-run apt-cacher
#
# and then you can run containers with:
# docker run -t -i --rm -e http_proxy http://dockerhost:3142/ debian bash
#
# Here, `dockerhost` is the IP address or FQDN of a host running the Docker daemon
# which acts as an APT proxy server.
FROM ubuntu
MAINTAINER SvenDowideit@docker.com
VOLUME ["/var/cache/apt-cacher-ng"]
RUN apt-get update && apt-get install -y apt-cacher-ng
EXPOSE 3142
CMD chmod 777 /var/cache/apt-cacher-ng && /etc/init.d/apt-cacher-ng start && tail -f /var/log/apt-cacher-ng/*
To build the image using:
$ docker build -t eg_apt_cacher_ng .
Then run it, mapping the exposed port to one on the host
$ docker run -d -p 3142:3142 --name test_apt_cacher_ng eg_apt_cacher_ng
To see the logfiles that are `tailed` in the default command, you can
use:
$ docker logs -f test_apt_cacher_ng
To get your Debian-based containers to use the proxy, you have following options
1. Add an apt Proxy setting
`echo 'Acquire::http { Proxy "http://dockerhost:3142"; };' >> /etc/apt/conf.d/01proxy`
2. Set an environment variable:
`http_proxy=http://dockerhost:3142/`
3. Change your `sources.list` entries to start with
`http://dockerhost:3142/`
4. Link Debian-based containers to the APT proxy container using `--link`
5. Create a custom network of an APT proxy container with Debian-based containers.
**Option 1** injects the settings safely into your apt configuration in
a local version of a common base:
FROM ubuntu
RUN echo 'Acquire::http { Proxy "http://dockerhost:3142"; };' >> /etc/apt/apt.conf.d/01proxy
RUN apt-get update && apt-get install -y vim git
# docker build -t my_ubuntu .
**Option 2** is good for testing, but will break other HTTP clients
which obey `http_proxy`, such as `curl`, `wget` and others:
$ docker run --rm -t -i -e http_proxy=http://dockerhost:3142/ debian bash
**Option 3** is the least portable, but there will be times when you
might need to do it and you can do it from your `Dockerfile`
too.
**Option 4** links Debian-containers to the proxy server using following command:
$ docker run -i -t --link test_apt_cacher_ng:apt_proxy -e http_proxy=http://apt_proxy:3142/ debian bash
**Option 5** creates a custom network of APT proxy server and Debian-based containers:
$ docker network create mynetwork
$ docker run -d -p 3142:3142 --net=mynetwork --name test_apt_cacher_ng eg_apt_cacher_ng
$ docker run --rm -it --net=mynetwork -e http_proxy=http://test_apt_cacher_ng:3142/ debian bash
Apt-cacher-ng has some tools that allow you to manage the repository,
and they can be used by leveraging the `VOLUME`
instruction, and the image we built to run the service:
$ docker run --rm -t -i --volumes-from test_apt_cacher_ng eg_apt_cacher_ng bash
$$ /usr/lib/apt-cacher-ng/distkill.pl
Scanning /var/cache/apt-cacher-ng, please wait...
Found distributions:
bla, taggedcount: 0
1. precise-security (36 index files)
2. wheezy (25 index files)
3. precise-updates (36 index files)
4. precise (36 index files)
5. wheezy-updates (18 index files)
Found architectures:
6. amd64 (36 index files)
7. i386 (24 index files)
WARNING: The removal action may wipe out whole directories containing
index files. Select d to see detailed list.
(Number nn: tag distribution or architecture nn; 0: exit; d: show details; r: remove tagged; q: quit): q
Finally, clean up after your test by stopping and removing the
container, and then removing the image.
$ docker stop test_apt_cacher_ng
$ docker rm test_apt_cacher_ng
$ docker rmi eg_apt_cacher_ng

View File

@@ -0,0 +1,235 @@
<!--[metadata]>
+++
title = "Dockerizing a Couchbase service"
description = "Dockerizing a Couchbase service"
keywords = ["docker, example, package installation, networking, couchbase"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing a Couchbase service
This example shows how to start a [Couchbase](http://couchbase.com) server using Docker Compose, configure it using its [REST API](http://developer.couchbase.com/documentation/server/4.0/rest-api/rest-endpoints-all.html), and query it.
Couchbase is an open source, document-oriented NoSQL database for modern web, mobile, and IoT applications. It is designed for ease of development and Internet-scale performance.
## Start Couchbase server
Couchbase Docker images are published at [Docker Hub](https://hub.docker.com/_/couchbase/).
Start Couchbase server as:
```
docker run -d --name db -p 8091-8093:8091-8093 -p 11210:11210 couchbase
```
The purpose of each port exposed is explained at [Couchbase Developer Portal - Network Configuration](http://developer.couchbase.com/documentation/server/4.1/install/install-ports.html).
Logs can be seen as:
```
docker logs db
Starting Couchbase Server -- Web UI available at http://<ip>:8091
```
> **Note**: The examples on this page assume that the Docker Host
> is reachable on `192.168.99.100`. Substitute `192.168.99.100` with
> the actual IP address of your Docker Host. If you're running
> Docker using Docker machine, you can obtain the IP address
> of the Docker host using `docker-machine ip <MACHINE-NAME>`.
The logs show that Couchbase console can be accessed at http://192.168.99.100:8091. The default username is `Administrator` and the password is `password`.
## Configure Couchbase Docker container
By default, Couchbase server needs to be configured using the console before it can be used. This can be simplified by configuring it using the REST API.
### Configure memory for Data and Index service
Data, Query and Index are three different services that can be configured on a Couchbase instance. Each service has different operating needs. For example, Query is CPU intensive operation and so requires a faster processor. Index is disk heavy and so requires a faster solid state drive. Data needs to be read/written fast and so requires more memory.
Memory needs to be configured for Data and Index service only.
```
curl -v -X POST http://192.168.99.100:8091/pools/default -d memoryQuota=300 -d indexMemoryQuota=300
* Hostname was NOT found in DNS cache
* Trying 192.168.99.100...
* Connected to 192.168.99.100 (192.168.99.100) port 8091 (#0)
> POST /pools/default HTTP/1.1
> User-Agent: curl/7.37.1
> Host: 192.168.99.100:8091
> Accept: */*
> Content-Length: 36
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 36 out of 36 bytes
< HTTP/1.1 401 Unauthorized
< WWW-Authenticate: Basic realm="Couchbase Server Admin / REST"
* Server Couchbase Server is not blacklisted
< Server: Couchbase Server
< Pragma: no-cache
< Date: Wed, 25 Nov 2015 22:48:16 GMT
< Content-Length: 0
< Cache-Control: no-cache
<
* Connection #0 to host 192.168.99.100 left intact
```
The command shows an HTTP POST request to the REST endpoint `/pools/default`. The host is the IP address of the Docker machine. The port is the exposed port of Couchbase server. The memory and index quota for the server are passed in the request.
### Configure Data, Query, and Index services
All three services, or only one of them, can be configured on each instance. This allows different Couchbase instances to use affinities and setup services accordingly. For example, if Docker host is running a machine with solid-state drive then only Data service can be started.
```
curl -v http://192.168.99.100:8091/node/controller/setupServices -d 'services=kv%2Cn1ql%2Cindex'
* Hostname was NOT found in DNS cache
* Trying 192.168.99.100...
* Connected to 192.168.99.100 (192.168.99.100) port 8091 (#0)
> POST /node/controller/setupServices HTTP/1.1
> User-Agent: curl/7.37.1
> Host: 192.168.99.100:8091
> Accept: */*
> Content-Length: 26
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 26 out of 26 bytes
< HTTP/1.1 200 OK
* Server Couchbase Server is not blacklisted
< Server: Couchbase Server
< Pragma: no-cache
< Date: Wed, 25 Nov 2015 22:49:51 GMT
< Content-Length: 0
< Cache-Control: no-cache
<
* Connection #0 to host 192.168.99.100 left intact
```
The command shows an HTTP POST request to the REST endpoint `/node/controller/setupServices`. The command shows that all three services are configured for the Couchbase server. The Data service is identified by `kv`, Query service is identified by `n1ql` and Index service identified by `index`.
### Setup credentials for the Couchbase server
Sets the username and password credentials that will subsequently be used for managing the Couchbase server.
```
curl -v -X POST http://192.168.99.100:8091/settings/web -d port=8091 -d username=Administrator -d password=password
* Hostname was NOT found in DNS cache
* Trying 192.168.99.100...
* Connected to 192.168.99.100 (192.168.99.100) port 8091 (#0)
> POST /settings/web HTTP/1.1
> User-Agent: curl/7.37.1
> Host: 192.168.99.100:8091
> Accept: */*
> Content-Length: 50
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 50 out of 50 bytes
< HTTP/1.1 200 OK
* Server Couchbase Server is not blacklisted
< Server: Couchbase Server
< Pragma: no-cache
< Date: Wed, 25 Nov 2015 22:50:43 GMT
< Content-Type: application/json
< Content-Length: 44
< Cache-Control: no-cache
<
* Connection #0 to host 192.168.99.100 left intact
{"newBaseUri":"http://192.168.99.100:8091/"}
```
The command shows an HTTP POST request to the REST endpoint `/settings/web`. The user name and password credentials are passed in the request.
### Install sample data
The Couchbase server can be easily load some sample data in the Couchbase instance.
```
curl -v -u Administrator:password -X POST http://192.168.99.100:8091/sampleBuckets/install -d '["travel-sample"]'
* Hostname was NOT found in DNS cache
* Trying 192.168.99.100...
* Connected to 192.168.99.100 (192.168.99.100) port 8091 (#0)
* Server auth using Basic with user 'Administrator'
> POST /sampleBuckets/install HTTP/1.1
> Authorization: Basic QWRtaW5pc3RyYXRvcjpwYXNzd29yZA==
> User-Agent: curl/7.37.1
> Host: 192.168.99.100:8091
> Accept: */*
> Content-Length: 17
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 17 out of 17 bytes
< HTTP/1.1 202 Accepted
* Server Couchbase Server is not blacklisted
< Server: Couchbase Server
< Pragma: no-cache
< Date: Wed, 25 Nov 2015 22:51:51 GMT
< Content-Type: application/json
< Content-Length: 2
< Cache-Control: no-cache
<
* Connection #0 to host 192.168.99.100 left intact
[]
```
The command shows an HTTP POST request to the REST endpoint `/sampleBuckets/install`. The name of the sample bucket is passed in the request.
Congratulations, you are now running a Couchbase container, fully configured using the REST API.
## Query Couchbase using CBQ
[CBQ](http://developer.couchbase.com/documentation/server/4.1/cli/cbq-tool.html), short for Couchbase Query, is a CLI tool that allows to create, read, update, and delete JSON documents on a Couchbase server. This tool is installed as part of the Couchbase Docker image.
Run CBQ tool:
```
docker run -it --link db:db couchbase cbq --engine http://db:8093
Couchbase query shell connected to http://db:8093/ . Type Ctrl-D to exit.
cbq>
```
`--engine` parameter to CBQ allows to specify the Couchbase server host and port running on the Docker host. For host, typically the host name or IP address of the host where Couchbase server is running is provided. In this case, the container name used when starting the container, `db`, can be used. `8093` port listens for all incoming queries.
Couchbase allows to query JSON documents using [N1QL](http://developer.couchbase.com/documentation/server/4.1/n1ql/n1ql-language-reference/index.html). N1QL is a comprehensive, declarative query language that brings SQL-like query capabilities to JSON documents.
Query the database by running a N1QL query:
```
cbq> select * from `travel-sample` limit 1;
{
"requestID": "97816771-3c25-4a1d-9ea8-eb6ad8a51919",
"signature": {
"*": "*"
},
"results": [
{
"travel-sample": {
"callsign": "MILE-AIR",
"country": "United States",
"iata": "Q5",
"icao": "MLA",
"id": 10,
"name": "40-Mile Air",
"type": "airline"
}
}
],
"status": "success",
"metrics": {
"elapsedTime": "60.872423ms",
"executionTime": "60.792258ms",
"resultCount": 1,
"resultSize": 300
}
}
```
## Couchbase Web Console
[Couchbase Web Console](http://developer.couchbase.com/documentation/server/4.1/admin/ui-intro.html) is a console that allows to manage a Couchbase instance. It can be seen at:
http://192.168.99.100:8091/
Make sure to replace the IP address with the IP address of your Docker Machine or `localhost` if Docker is running locally.
![Couchbase Web Console](couchbase/web-console.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

View File

@@ -0,0 +1,49 @@
<!--[metadata]>
+++
title = "Dockerizing a CouchDB service"
description = "Sharing data between 2 couchdb databases"
keywords = ["docker, example, package installation, networking, couchdb, data volumes"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing a CouchDB service
> **Note**:
> - **If you don't like sudo** then see [*Giving non-root
> access*](../installation/binaries.md#giving-non-root-access)
Here's an example of using data volumes to share the same data between
two CouchDB containers. This could be used for hot upgrades, testing
different versions of CouchDB on the same data, etc.
## Create first database
Note that we're marking `/var/lib/couchdb` as a data volume.
$ COUCH1=$(docker run -d -p 5984 -v /var/lib/couchdb shykes/couchdb:2013-05-03)
## Add data to the first database
We're assuming your Docker host is reachable at `localhost`. If not,
replace `localhost` with the public IP of your Docker host.
$ HOST=localhost
$ URL="http://$HOST:$(docker port $COUCH1 5984 | grep -o '[1-9][0-9]*$')/_utils/"
$ echo "Navigate to $URL in your browser, and use the couch interface to add data"
## Create second database
This time, we're requesting shared access to `$COUCH1`'s volumes.
$ COUCH2=$(docker run -d -p 5984 --volumes-from $COUCH1 shykes/couchdb:2013-05-03)
## Browse data on the second database
$ HOST=localhost
$ URL="http://$HOST:$(docker port $COUCH2 5984 | grep -o '[1-9][0-9]*$')/_utils/"
$ echo "Navigate to $URL in your browser. You should see the same data as in the first database"'!'
Congratulations, you are now running two Couchdb containers, completely
isolated from each other *except* for their data.

View File

@@ -0,0 +1,23 @@
<!--[metadata]>
+++
title = "Dockerize an application"
description = "Provides examples for using Docker"
keywords = ["dockerize, dockerizing apps, dockerizing applications, container, containers"]
[menu.main]
identifier = "engine_dockerize"
parent="engine_use"
weight = 8
+++
<![end-metadata]-->
# Dockerize an application
This section contains the following:
* [Dockerizing MongoDB](mongodb.md)
* [Dockerizing PostgreSQL](postgresql_service.md)
* [Dockerizing a CouchDB service](couchdb_data_volumes.md)
* [Dockerizing a Node.js web app](nodejs_web_app.md)
* [Dockerizing a Redis service](running_redis_service.md)
* [Dockerizing an apt-cacher-ng service](apt-cacher-ng.md)
* [Dockerizing applications: A 'Hello world'](../userguide/containers/dockerizing.md)

View File

@@ -0,0 +1,177 @@
<!--[metadata]>
+++
title = "Dockerizing MongoDB"
description = "Creating a Docker image with MongoDB pre-installed using a Dockerfile and sharing the image on Docker Hub"
keywords = ["docker, dockerize, dockerizing, article, example, docker.io, platform, package, installation, networking, mongodb, containers, images, image, sharing, dockerfile, build, auto-building, framework"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing MongoDB
## Introduction
In this example, we are going to learn how to build a Docker image with
MongoDB pre-installed. We'll also see how to `push` that image to the
[Docker Hub registry](https://hub.docker.com) and share it with others!
> **Note:** This guide will show the mechanics of building a MongoDB container, but
> you will probably want to use the official image on [Docker Hub]( https://registry.hub.docker.com/_/mongo/)
Using Docker and containers for deploying [MongoDB](https://www.mongodb.org/)
instances will bring several benefits, such as:
- Easy to maintain, highly configurable MongoDB instances;
- Ready to run and start working within milliseconds;
- Based on globally accessible and shareable images.
> **Note:**
>
> If you do **_not_** like `sudo`, you might want to check out:
> [*Giving non-root access*](../installation/binaries.md#giving-non-root-access).
## Creating a Dockerfile for MongoDB
Let's create our `Dockerfile` and start building it:
$ nano Dockerfile
Although optional, it is handy to have comments at the beginning of a
`Dockerfile` explaining its purpose:
# Dockerizing MongoDB: Dockerfile for building MongoDB images
# Based on ubuntu:latest, installs MongoDB following the instructions from:
# http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
> **Tip:** `Dockerfile`s are flexible. However, they need to follow a certain
> format. The first item to be defined is the name of an image, which becomes
> the *parent* of your *Dockerized MongoDB* image.
We will build our image using the latest version of Ubuntu from the
[Docker Hub Ubuntu](https://registry.hub.docker.com/_/ubuntu/) repository.
# Format: FROM repository[:version]
FROM ubuntu:latest
Continuing, we will declare the `MAINTAINER` of the `Dockerfile`:
# Format: MAINTAINER Name <email@addr.ess>
MAINTAINER M.Y. Name <myname@addr.ess>
> **Note:** Although Ubuntu systems have MongoDB packages, they are likely to
> be outdated. Therefore in this example, we will use the official MongoDB
> packages.
We will begin with importing the MongoDB public GPG key. We will also create
a MongoDB repository file for the package manager.
# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
RUN echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list
After this initial preparation we can update our packages and install MongoDB.
# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get install -y mongodb-org
> **Tip:** You can install a specific version of MongoDB by using a list
> of required packages with versions, e.g.:
>
> RUN apt-get update && apt-get install -y mongodb-org=3.0.1 mongodb-org-server=3.0.1 mongodb-org-shell=3.0.1 mongodb-org-mongos=3.0.1 mongodb-org-tools=3.0.1
MongoDB requires a data directory. Let's create it as the final step of our
installation instructions.
# Create the MongoDB data directory
RUN mkdir -p /data/db
Lastly we set the `ENTRYPOINT` which will tell Docker to run `mongod` inside
the containers launched from our MongoDB image. And for ports, we will use
the `EXPOSE` instruction.
# Expose port 27017 from the container to the host
EXPOSE 27017
# Set usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]
Now save the file and let's build our image.
> **Note:**
>
> The full version of this `Dockerfile` can be found [here](https://github.com/docker/docker/blob/master/docs/examples/mongodb/Dockerfile).
## Building the MongoDB Docker image
With our `Dockerfile`, we can now build the MongoDB image using Docker. Unless
experimenting, it is always a good practice to tag Docker images by passing the
`--tag` option to `docker build` command.
# Format: docker build --tag/-t <user-name>/<repository> .
# Example:
$ docker build --tag my/repo .
Once this command is issued, Docker will go through the `Dockerfile` and build
the image. The final image will be tagged `my/repo`.
## Pushing the MongoDB image to Docker Hub
All Docker image repositories can be hosted and shared on
[Docker Hub](https://hub.docker.com) with the `docker push` command. For this,
you need to be logged-in.
# Log-in
$ docker login
Username:
..
# Push the image
# Format: docker push <user-name>/<repository>
$ docker push my/repo
The push refers to a repository [my/repo] (len: 1)
Sending image list
Pushing repository my/repo (1 tags)
..
## Using the MongoDB image
Using the MongoDB image we created, we can run one or more MongoDB instances
as daemon process(es).
# Basic way
# Usage: docker run --name <name for container> -d <user-name>/<repository>
$ docker run -p 27017:27017 --name mongo_instance_001 -d my/repo
# Dockerized MongoDB, lean and mean!
# Usage: docker run --name <name for container> -d <user-name>/<repository> --noprealloc --smallfiles
$ docker run -p 27017:27017 --name mongo_instance_001 -d my/repo --smallfiles
# Checking out the logs of a MongoDB container
# Usage: docker logs <name for container>
$ docker logs mongo_instance_001
# Playing with MongoDB
# Usage: mongo --port <port you get from `docker ps`>
$ mongo --port 27017
# If using docker-machine
# Usage: mongo --port <port you get from `docker ps`> --host <ip address from `docker-machine ip VM_NAME`>
$ mongo --port 27017 --host 192.168.59.103
> **Tip:**
If you want to run two containers on the same engine, then you will need to map
the exposed port to two different ports on the host
# Start two containers and map the ports
$ docker run -p 28001:27017 --name mongo_instance_001 -d my/repo
$ docker run -p 28002:27017 --name mongo_instance_002 -d my/repo
# Now you can connect to each MongoDB instance on the two ports
$ mongo --port 28001
$ mongo --port 28002
- [Linking containers](../userguide/networking/default_network/dockerlinks.md)
- [Cross-host linking containers](../admin/ambassador_pattern_linking.md)
- [Creating an Automated Build](https://docs.docker.com/docker-hub/builds/)

View File

@@ -0,0 +1,22 @@
# Dockerizing MongoDB: Dockerfile for building MongoDB images
# Based on ubuntu:latest, installs MongoDB following the instructions from:
# http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
FROM ubuntu:latest
MAINTAINER Docker
# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
RUN echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list
# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get install -y mongodb-org
# Create the MongoDB data directory
RUN mkdir -p /data/db
# Expose port #27017 from the container to the host
EXPOSE 27017
# Set /usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]

View File

@@ -0,0 +1,199 @@
<!--[metadata]>
+++
title = "Dockerizing a Node.js web app"
description = "Installing and running a Node.js app with Docker"
keywords = ["docker, example, package installation, node, centos"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing a Node.js web app
> **Note**:
> - **If you don't like sudo** then see [*Giving non-root
> access*](../installation/binaries.md#giving-non-root-access)
The goal of this example is to show you how you can build your own
Docker images from a parent image using a `Dockerfile`
. We will do that by making a simple Node.js hello world web
application running on CentOS. You can get the full source code at[https://github.com/enokd/docker-node-hello/](https://github.com/enokd/docker-node-hello/).
## Create Node.js app
First, create a directory `src` where all the files
would live. Then create a `package.json` file that
describes your app and its dependencies:
{
"name": "docker-centos-hello",
"private": true,
"version": "0.0.1",
"description": "Node.js Hello world app on CentOS using docker",
"author": "Daniel Gasienica <daniel@gasienica.ch>",
"dependencies": {
"express": "3.2.4"
}
}
Then, create an `index.js` file that defines a web
app using the [Express.js](http://expressjs.com/) framework:
var express = require('express');
// Constants
var PORT = 8080;
// App
var app = express();
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
In the next steps, we'll look at how you can run this app inside a
CentOS container using Docker. First, you'll need to build a Docker
image of your app.
## Creating a Dockerfile
Create an empty file called `Dockerfile`:
touch Dockerfile
Open the `Dockerfile` in your favorite text editor
Define the parent image you want to use to build your own image on
top of. Here, we'll use
[CentOS](https://registry.hub.docker.com/_/centos/) (tag: `centos6`)
available on the [Docker Hub](https://hub.docker.com/):
FROM centos:centos6
Since we're building a Node.js app, you'll have to install Node.js as
well as npm on your CentOS image. Node.js is required to run your app
and npm is required to install your app's dependencies defined in
`package.json`. To install the right package for
CentOS, we'll use the instructions from the [Node.js wiki](
https://github.com/joyent/node/wiki/Installing-Node.js-
via-package-manager#rhelcentosscientific-linux-6):
# Enable Extra Packages for Enterprise Linux (EPEL) for CentOS
RUN yum install -y epel-release
# Install Node.js and npm
RUN yum install -y nodejs npm
Install your app dependencies using the `npm` binary:
# Install app dependencies
COPY package.json /src/package.json
RUN cd /src; npm install
To bundle your app's source code inside the Docker image, use the `COPY`
instruction:
# Bundle app source
COPY . /src
Your app binds to port `8080` so you'll use the `EXPOSE` instruction to have
it mapped by the `docker` daemon:
EXPOSE 8080
Last but not least, define the command to run your app using `CMD` which
defines your runtime, i.e. `node`, and the path to our app, i.e. `src/index.js`
(see the step where we added the source to the container):
CMD ["node", "/src/index.js"]
Your `Dockerfile` should now look like this:
FROM centos:centos6
# Enable Extra Packages for Enterprise Linux (EPEL) for CentOS
RUN yum install -y epel-release
# Install Node.js and npm
RUN yum install -y nodejs npm
# Install app dependencies
COPY package.json /src/package.json
RUN cd /src; npm install
# Bundle app source
COPY . /src
EXPOSE 8080
CMD ["node", "/src/index.js"]
## Building your image
Go to the directory that has your `Dockerfile` and run the following command
to build a Docker image. The `-t` flag lets you tag your image so it's easier
to find later using the `docker images` command:
$ docker build -t <your username>/centos-node-hello .
Your image will now be listed by Docker:
$ docker images
# Example
REPOSITORY TAG ID CREATED
centos centos6 539c0211cd76 8 weeks ago
<your username>/centos-node-hello latest d64d3505b0d2 2 hours ago
## Run the image
Running your image with `-d` runs the container in detached mode, leaving the
container running in the background. The `-p` flag redirects a public port to
a private port in the container. Run the image you previously built:
$ docker run -p 49160:8080 -d <your username>/centos-node-hello
Print the output of your app:
# Get container ID
$ docker ps
# Print app output
$ docker logs <container id>
# Example
Running on http://localhost:8080
## Test
To test your app, get the port of your app that Docker mapped:
$ docker ps
# Example
ID IMAGE COMMAND ... PORTS
ecce33b30ebf <your username>/centos-node-hello:latest node /src/index.js 49160->8080
In the example above, Docker mapped the `8080` port of the container to `49160`.
Now you can call your app using `curl` (install if needed via:
`sudo apt-get install curl`):
$ curl -i localhost:49160
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 12
Date: Sun, 02 Jun 2013 03:53:22 GMT
Connection: keep-alive
Hello world
If you use Docker Machine on OS X, the port is actually mapped to the Docker
host VM, and you should use the following command:
$ curl $(docker-machine ip VM_NAME):49160
We hope this tutorial helped you get up and running with Node.js and
CentOS on Docker. You can get the full source code at
[https://github.com/enokd/docker-node-hello/](https://github.com/enokd/docker-node-hello/).

View File

@@ -0,0 +1,49 @@
#
# example Dockerfile for https://docs.docker.com/examples/postgresql_service/
#
FROM ubuntu
MAINTAINER SvenDowideit@docker.com
# Add the PostgreSQL PGP key to verify their Debian packages.
# It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
# Add PostgreSQL's repository. It contains the most recent stable release
# of PostgreSQL, ``9.3``.
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
# Install ``python-software-properties``, ``software-properties-common`` and PostgreSQL 9.3
# There are some warnings (in red) that show up during the build. You can hide
# them by prefixing each apt-get statement with DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3
# Note: The official Debian and Ubuntu images automatically ``apt-get clean``
# after each ``apt-get``
# Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed``
USER postgres
# Create a PostgreSQL role named ``docker`` with ``docker`` as the password and
# then create a database `docker` owned by the ``docker`` role.
# Note: here we use ``&&\`` to run commands one after the other - the ``\``
# allows the RUN command to span multiple lines.
RUN /etc/init.d/postgresql start &&\
psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\
createdb -O docker docker
# Adjust PostgreSQL configuration so that remote connections to the
# database are possible.
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf
# And add ``listen_addresses`` to ``/etc/postgresql/9.3/main/postgresql.conf``
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf
# Expose the PostgreSQL port
EXPOSE 5432
# Add VOLUMEs to allow backup of config, logs and databases
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
# Set the default command to run when starting the container
CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]

View File

@@ -0,0 +1,153 @@
<!--[metadata]>
+++
title = "Dockerizing PostgreSQL"
description = "Running and installing a PostgreSQL service"
keywords = ["docker, example, package installation, postgresql"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing PostgreSQL
> **Note**:
> - **If you don't like sudo** then see [*Giving non-root
> access*](../installation/binaries.md#giving-non-root-access)
## Installing PostgreSQL on Docker
Assuming there is no Docker image that suits your needs on the [Docker
Hub](http://hub.docker.com), you can create one yourself.
Start by creating a new `Dockerfile`:
> **Note**:
> This PostgreSQL setup is for development-only purposes. Refer to the
> PostgreSQL documentation to fine-tune these settings so that it is
> suitably secure.
#
# example Dockerfile for https://docs.docker.com/examples/postgresql_service/
#
FROM ubuntu
MAINTAINER SvenDowideit@docker.com
# Add the PostgreSQL PGP key to verify their Debian packages.
# It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
# Add PostgreSQL's repository. It contains the most recent stable release
# of PostgreSQL, ``9.3``.
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
# Install ``python-software-properties``, ``software-properties-common`` and PostgreSQL 9.3
# There are some warnings (in red) that show up during the build. You can hide
# them by prefixing each apt-get statement with DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3
# Note: The official Debian and Ubuntu images automatically ``apt-get clean``
# after each ``apt-get``
# Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed``
USER postgres
# Create a PostgreSQL role named ``docker`` with ``docker`` as the password and
# then create a database `docker` owned by the ``docker`` role.
# Note: here we use ``&&\`` to run commands one after the other - the ``\``
# allows the RUN command to span multiple lines.
RUN /etc/init.d/postgresql start &&\
psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\
createdb -O docker docker
# Adjust PostgreSQL configuration so that remote connections to the
# database are possible.
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf
# And add ``listen_addresses`` to ``/etc/postgresql/9.3/main/postgresql.conf``
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf
# Expose the PostgreSQL port
EXPOSE 5432
# Add VOLUMEs to allow backup of config, logs and databases
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
# Set the default command to run when starting the container
CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]
Build an image from the Dockerfile assign it a name.
$ docker build -t eg_postgresql .
And run the PostgreSQL server container (in the foreground):
$ docker run --rm -P --name pg_test eg_postgresql
There are 2 ways to connect to the PostgreSQL server. We can use [*Link
Containers*](../userguide/networking/default_network/dockerlinks.md), or we can access it from our host
(or the network).
> **Note**:
> The `--rm` removes the container and its image when
> the container exits successfully.
### Using container linking
Containers can be linked to another container's ports directly using
`-link remote_name:local_alias` in the client's
`docker run`. This will set a number of environment
variables that can then be used to connect:
$ docker run --rm -t -i --link pg_test:pg eg_postgresql bash
postgres@7ef98b1b7243:/$ psql -h $PG_PORT_5432_TCP_ADDR -p $PG_PORT_5432_TCP_PORT -d docker -U docker --password
### Connecting from your host system
Assuming you have the postgresql-client installed, you can use the
host-mapped port to test as well. You need to use `docker ps`
to find out what local host port the container is mapped to
first:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5e24362f27f6 eg_postgresql:latest /usr/lib/postgresql/ About an hour ago Up About an hour 0.0.0.0:49153->5432/tcp pg_test
$ psql -h localhost -p 49153 -d docker -U docker --password
### Testing the database
Once you have authenticated and have a `docker =#`
prompt, you can create a table and populate it.
psql (9.3.1)
Type "help" for help.
$ docker=# CREATE TABLE cities (
docker(# name varchar(80),
docker(# location point
docker(# );
CREATE TABLE
$ docker=# INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)');
INSERT 0 1
$ docker=# select * from cities;
name | location
---------------+-----------
San Francisco | (-194,53)
(1 row)
### Using the container volumes
You can use the defined volumes to inspect the PostgreSQL log files and
to backup your configuration and data:
$ docker run --rm --volumes-from pg_test -t -i busybox sh
/ # ls
bin etc lib linuxrc mnt proc run sys usr
dev home lib64 media opt root sbin tmp var
/ # ls /etc/postgresql/9.3/main/
environment pg_hba.conf postgresql.conf
pg_ctl.conf pg_ident.conf start.conf
/tmp # ls /var/log
ldconfig postgresql

View File

@@ -0,0 +1,89 @@
<!--[metadata]>
+++
title = "Dockerizing a Redis service"
description = "Installing and running an redis service"
keywords = ["docker, example, package installation, networking, redis"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing a Redis service
Very simple, no frills, Redis service attached to a web application
using a link.
## Create a Docker container for Redis
Firstly, we create a `Dockerfile` for our new Redis
image.
FROM ubuntu:14.04
RUN apt-get update && apt-get install -y redis-server
EXPOSE 6379
ENTRYPOINT ["/usr/bin/redis-server"]
Next we build an image from our `Dockerfile`.
Replace `<your username>` with your own user name.
$ docker build -t <your username>/redis .
## Run the service
Use the image we've just created and name your container `redis`.
Running the service with `-d` runs the container in detached mode, leaving
the container running in the background.
Importantly, we're not exposing any ports on our container. Instead
we're going to use a container link to provide access to our Redis
database.
$ docker run --name redis -d <your username>/redis
## Create your web application container
Next we can create a container for our application. We're going to use
the `-link` flag to create a link to the `redis` container we've just
created with an alias of `db`. This will create a secure tunnel to the
`redis` container and expose the Redis instance running inside that
container to only this container.
$ docker run --link redis:db -i -t ubuntu:14.04 /bin/bash
Once inside our freshly created container we need to install Redis to
get the `redis-cli` binary to test our connection.
$ sudo apt-get update
$ sudo apt-get install redis-server
$ sudo service redis-server stop
As we've used the `--link redis:db` option, Docker
has created some environment variables in our web application container.
$ env | grep DB_
# Should return something similar to this with your values
DB_NAME=/violet_wolf/db
DB_PORT_6379_TCP_PORT=6379
DB_PORT=tcp://172.17.0.33:6379
DB_PORT_6379_TCP=tcp://172.17.0.33:6379
DB_PORT_6379_TCP_ADDR=172.17.0.33
DB_PORT_6379_TCP_PROTO=tcp
We can see that we've got a small list of environment variables prefixed
with `DB`. The `DB` comes from the link alias specified when we launched
the container. Let's use the `DB_PORT_6379_TCP_ADDR` variable to connect to
our Redis container.
$ redis-cli -h $DB_PORT_6379_TCP_ADDR
$ redis 172.17.0.33:6379>
$ redis 172.17.0.33:6379> set docker awesome
OK
$ redis 172.17.0.33:6379> get docker
"awesome"
$ redis 172.17.0.33:6379> exit
We could easily use this or other environment variables in our web
application to make a connection to our `redis`
container.

View File

@@ -0,0 +1,31 @@
# Riak
#
# VERSION 0.1.1
# Use the Ubuntu base image provided by dotCloud
FROM ubuntu:trusty
MAINTAINER Hector Castro hector@basho.com
# Install Riak repository before we do apt-get update, so that update happens
# in a single step
RUN apt-get install -q -y curl && \
curl -fsSL https://packagecloud.io/install/repositories/basho/riak/script.deb | sudo bash
# Install and setup project dependencies
RUN apt-get update && \
apt-get install -y supervisor riak=2.0.5-1
RUN mkdir -p /var/log/supervisor
RUN locale-gen en_US en_US.UTF-8
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# Configure Riak to accept connections from any host
RUN sed -i "s|listener.http.internal = 127.0.0.1:8098|listener.http.internal = 0.0.0.0:8098|" /etc/riak/riak.conf
RUN sed -i "s|listener.protobuf.internal = 127.0.0.1:8087|listener.protobuf.internal = 0.0.0.0:8087|" /etc/riak/riak.conf
# Expose Riak Protocol Buffers and HTTP interfaces
EXPOSE 8087 8098
CMD ["/usr/bin/supervisord"]

View File

@@ -0,0 +1,108 @@
<!--[metadata]>
+++
title = "Dockerizing a Riak service"
description = "Build a Docker image with Riak pre-installed"
keywords = ["docker, example, package installation, networking, riak"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing a Riak service
The goal of this example is to show you how to build a Docker image with
Riak pre-installed.
## Creating a Dockerfile
Create an empty file called `Dockerfile`:
$ touch Dockerfile
Next, define the parent image you want to use to build your image on top
of. We'll use [Ubuntu](https://registry.hub.docker.com/_/ubuntu/) (tag:
`trusty`), which is available on [Docker Hub](https://hub.docker.com):
# Riak
#
# VERSION 0.1.1
# Use the Ubuntu base image provided by dotCloud
FROM ubuntu:trusty
MAINTAINER Hector Castro hector@basho.com
After that, we install the curl which is used to download the repository setup
script and we download the setup script and run it.
# Install Riak repository before we do apt-get update, so that update happens
# in a single step
RUN apt-get install -q -y curl && \
curl -fsSL https://packagecloud.io/install/repositories/basho/riak/script.deb | sudo bash
Then we install and setup a few dependencies:
- `supervisor` is used manage the Riak processes
- `riak=2.0.5-1` is the Riak package coded to version 2.0.5
<!-- -->
# Install and setup project dependencies
RUN apt-get update && \
apt-get install -y supervisor riak=2.0.5-1
RUN mkdir -p /var/log/supervisor
RUN locale-gen en_US en_US.UTF-8
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
After that, we modify Riak's configuration:
# Configure Riak to accept connections from any host
RUN sed -i "s|listener.http.internal = 127.0.0.1:8098|listener.http.internal = 0.0.0.0:8098|" /etc/riak/riak.conf
RUN sed -i "s|listener.protobuf.internal = 127.0.0.1:8087|listener.protobuf.internal = 0.0.0.0:8087|" /etc/riak/riak.conf
Then, we expose the Riak Protocol Buffers and HTTP interfaces:
# Expose Riak Protocol Buffers and HTTP interfaces
EXPOSE 8087 8098
Finally, run `supervisord` so that Riak is started:
CMD ["/usr/bin/supervisord"]
## Create a supervisord configuration file
Create an empty file called `supervisord.conf`. Make
sure it's at the same directory level as your `Dockerfile`:
touch supervisord.conf
Populate it with the following program definitions:
[supervisord]
nodaemon=true
[program:riak]
command=bash -c "/usr/sbin/riak console"
numprocs=1
autostart=true
autorestart=true
user=riak
environment=HOME="/var/lib/riak"
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
## Build the Docker image for Riak
Now you should be able to build a Docker image for Riak:
$ docker build -t "<yourname>/riak" .
## Next steps
Riak is a distributed database. Many production deployments consist of
[at least five nodes](
http://basho.com/why-your-riak-cluster-should-have-at-least-five-nodes/).
See the [docker-riak](https://github.com/hectcastro/docker-riak) project
details on how to deploy a Riak cluster using Docker and Pipework.

View File

@@ -0,0 +1,20 @@
# sshd
#
# VERSION 0.0.2
FROM ubuntu:14.04
MAINTAINER Sven Dowideit <SvenDowideit@docker.com>
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

View File

@@ -0,0 +1,84 @@
<!--[metadata]>
+++
title = "Dockerizing an SSH service"
description = "Installing and running an SSHd service on Docker"
keywords = ["docker, example, package installation, networking"]
[menu.main]
parent = "engine_dockerize"
+++
<![end-metadata]-->
# Dockerizing an SSH daemon service
## Build an `eg_sshd` image
The following `Dockerfile` sets up an SSHd service in a container that you
can use to connect to and inspect other container's volumes, or to get
quick access to a test container.
# sshd
#
# VERSION 0.0.2
FROM ubuntu:14.04
MAINTAINER Sven Dowideit <SvenDowideit@docker.com>
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
Build the image using:
$ docker build -t eg_sshd .
## Run a `test_sshd` container
Then run it. You can then use `docker port` to find out what host port
the container's port 22 is mapped to:
$ docker run -d -P --name test_sshd eg_sshd
$ docker port test_sshd 22
0.0.0.0:49154
And now you can ssh as `root` on the container's IP address (you can find it
with `docker inspect`) or on port `49154` of the Docker daemon's host IP address
(`ip address` or `ifconfig` can tell you that) or `localhost` if on the
Docker daemon host:
$ ssh root@192.168.1.2 -p 49154
# The password is ``screencast``.
$$
## Environment variables
Using the `sshd` daemon to spawn shells makes it complicated to pass environment
variables to the user's shell via the normal Docker mechanisms, as `sshd` scrubs
the environment before it starts the shell.
If you're setting values in the `Dockerfile` using `ENV`, you'll need to push them
to a shell initialization file like the `/etc/profile` example in the `Dockerfile`
above.
If you need to pass`docker run -e ENV=value` values, you will need to write a
short script to do the same before you start `sshd -D` and then replace the
`CMD` with that script.
## Clean up
Finally, clean up after your test by stopping and removing the
container, and then removing the image.
$ docker stop test_sshd
$ docker rm test_sshd
$ docker rmi eg_sshd

View File

@@ -0,0 +1,12 @@
[supervisord]
nodaemon=true
[program:riak]
command=bash -c "/usr/sbin/riak console"
numprocs=1
autostart=true
autorestart=true
user=riak
environment=HOME="/var/lib/riak"
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log