您的位置:首页 > 运维架构 > Docker

Docker-compose构建nginx反向代理实例

2017-09-23 14:09 741 查看
首先第一步安装启动docker在这里我就不演示了

docker compose项目。

compose简介

compose项目来源于之前的fig项目,使用python语言编写。compose项目主要用于编排部署docker的应用,本身与docker/swarm配合度很高

docker compose是docker编排服务的一部分,可以让用户在其他平台上快速的安装docker,dockercompose属于一个应用层的服务,用户可以定义哪个容器组运行哪个应用,它支持动态改变应用。

dockerfile可以让用户管理一个单独的容器,而compose则允许用户在一个模版yaml格式中定义一个相关联的容器,例如一个调度器,两个web服务器等。






一、我们先做一个基础的环境,用dockerfile做一个apache镜像。

以下是Apache的dockerfile。

#FROM docker.io/centos:centos6
MAINTAINER yankerp@jy.com
RUN yum install -y httpd net-tools iputils
RUN sed 's/#ServerName www.example.com:80/ServerName www.benet.com/g' /etc/httpd/conf/httpd.conf
EXPOSE 80
CMD ["/usr/sbin/httpd","-DFOREGROUND"]


1.编写完成之后运行dockerfile
# docker build -t centos:http .
Sending build context to Docker daemon 2.048 kB
Step 1 : FROM docker.io/centos:centos6
Trying to pull repository docker.io/library/centos ...
centos6: Pulling from docker.io/library/centos

b26de5a391ad: Downloading [=========================> ] 2.701 MB/70.04 MB
2.运行完成之后查看是否有http的镜像

# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              http                33e4acf38103        24 seconds ago      302 MB
docker.io/centos    centos6             5dedbd63518e        9 days ago          194.3 MB


3.编写nginx-dockerfile,以下的nginx的dockerfile

#images of nginx
FROM docker.io/centos:centos6
RUN yum install -y pcre-devel wget net-tools gcc zlib zlib-devel make openssl-devel
RUN useradd -M -s /sbin/nologin nginx
ADD http://nginx.org/download/nginx-1.6.2.tar.gz .
RUN tar zxvf nginx-1.6.2.tar.gz
RUN mkdir -p /usr/local/nginx
RUN cd nginx-1.6.2 && ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module && make && make install
RUN ln -s /usr/local/nginx/sbin/* /usr/local/sbin/
copy nginx.conf /usr/local/nginx/conf/nginx.conf
expose 80
CMD ["nginx"]


4.注意以上红色字段,我们需要拷贝一份nginx在当前目录。以下是nginx主配置内容

# ls
dockerfile  nginx.conf
vim nginx.conf
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
worker_connections  1024;
}

http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
upstream yankerp{
server Apache1:80 weight=1;
server Apache2:80 weight=1;
server Apache3:80 weight=1;
}
server {
listen       80;
server_name  localhost;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {
root   html;
index  index.html index.htm;
proxy_pass http://yankerp; }

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1; #}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#    listen       8000;
#    listen       somename:8080;
#    server_name  somename  alias  another.alias;

#    location / {
#        root   html;
#        index  index.html index.htm;
#    }
#}

# HTTPS server
#
#server {
#    listen       443 ssl;
#    server_name  localhost;

#    ssl_certificate      cert.pem;
#    ssl_certificate_key  cert.key;

#    ssl_session_cache    shared:SSL:1m;
#    ssl_session_timeout  5m;

#    ssl_ciphers  HIGH:!aNULL:!MD5;
#    ssl_prefer_server_ciphers  on;

#    location / {
#        root   html;
#        index  index.html index.htm;
#    }
#}

}
daemon off;


5.随后运行nginx-dockerfile 注意那个后面的小点,代表当前位置。

# docker build -t centos:nginx .
Sending build context to Docker daemon 6.144 kB
Step 1 : FROM docker.io/centos:centos6
---> 5dedbd63518e
Step 2 : RUN yum install -y pcre-devel wget net-tools gcc zlib zlib-devel make openssl-devel
---> Running in 4c25bd1ebd47
Loaded plugins: fastestmirror, ovl
Setting up Install Process


运行完之后我们查看是否有nginx镜像

# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              nginx               155c0c66b4fc        41 seconds ago      316.4 MB
centos              http                33e4acf38103        19 minutes ago      302 MB
docker.io/centos    centos6             5dedbd63518e        9 days ago          194.3 MB


二、安装compose,在安装docker-compose时,先安装pip,pip就相当于redhat里面的yum

以下是安装的过程



# wget https://bootstrap.pypa.io/get-pip.py --2017-09-23 14:56:25--  https://bootstrap.pypa.io/get-pip.py 正在解析主机 bootstrap.pypa.io (bootstrap.pypa.io)... 151.101.76.175
正在连接 bootstrap.pypa.io (bootstrap.pypa.io)|151.101.76.175|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1595408 (1.5M) [text/x-python]
正在保存至: “get-pip.py”

29% [=================================>                             ] 477,486     29.8KB/s 剩余 45s


python get-pip.py



# python get-pip.py
Collecting pip
Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)
100% |████████████████████████████████| 1.3MB 43kB/s
Collecting wheel
Downloading wheel-0.30.0-py2.py3-none-any.whl (49kB)
100% |████████████████████████████████| 51kB 21kB/s
Installing collected packages: pip, wheel
Successfully installed pip-9.0.1 wheel-0.30.0


安装完成时候在安装compose

# pip install docker-compose
Collecting docker-compose
Downloading docker_compose-1.16.1-py2.py3-none-any.whl (105kB)
100% |████████████████████████████████| 112kB 14kB/s
Collecting texttable<0.10,>=0.9.0 (from docker-compose)
Downloading texttable-0.9.1.tar.gz
Collecting backports.ssl-match-hostname>=3.5; python_version < "3.5" (from docker-compose)
Downloading backports.ssl_match_hostname-3.5.0.1.tar.gz
Collecting docker<3.0,>=2.5.1 (from docker-compose)
Downloading docker-2.5.1-py2.py3-none-any.whl (111kB)
100% |████████████████████████████████| 112kB 29kB/s
Collecting jsonschema<3,>=2.5.1 (from docker-compose)
Downloading jsonschema-2.6.0-py2.py3-none-any.whl
Collecting cached-property<2,>=1.2.0 (from docker-compose)
Downloading cached_property-1.3.1-py2.py3-none-any.whl
Requirement already satisfied: six<2,>=1.3.0 in /usr/lib/python2.7/site-packages (from docker-compose)
Collecting ipaddress>=1.0.16; python_version < "3.3" (from docker-compose)
Downloading ipaddress-1.0.18-py2-none-any.whl
Collecting enum34<2,>=1.0.4; python_version < "3.4" (from docker-compose)
Downloading enum34-1.1.6-py2-none-any.whl
Collecting websocket-client<1.0,>=0.32.0 (from docker-compose)
Downloading websocket_client-0.44.0-py2.py3-none-any.whl (199kB)
100% |████████████████████████████████| 204kB 29kB/s
Collecting PyYAML<4,>=3.10 (from docker-compose)
Downloading PyYAML-3.12.tar.gz (253kB)
100% |████████████████████████████████| 256kB 23kB/s
Collecting dockerpty<0.5,>=0.4.1 (from docker-compose)
Downloading dockerpty-0.4.1.tar.gz
Collecting requests!=2.11.0,<2.12,>=2.6.1 (from docker-compose)
Downloading requests-2.11.1-py2.py3-none-any.whl (514kB)
100% |████████████████████████████████| 522kB 24kB/s
Collecting docopt<0.7,>=0.6.1 (from docker-compose)
Downloading docopt-0.6.2.tar.gz
Collecting docker-pycreds>=0.2.1 (from docker<3.0,>=2.5.1->docker-compose)
Downloading docker_pycreds-0.2.1-py2.py3-none-any.whl
Collecting functools32; python_version == "2.7" (from jsonschema<3,>=2.5.1->docker-compose)
Downloading functools32-3.2.3-2.zip
Building wheels for collected packages: texttable, backports.ssl-match-hostname, PyYAML, dockerpty, docopt, functools32
Running setup.py bdist_wheel for texttable ... done
Stored in directory: /root/.cache/pip/wheels/9e/53/a3/e452dc385103ee8e1f0df7b3457974b580d52ce662ee5a16cc
Running setup.py bdist_wheel for backports.ssl-match-hostname ... done
Stored in directory: /root/.cache/pip/wheels/5d/72/36/b2a31507b613967b728edc33378a5ff2ada0f62855b93c5ae1
Running setup.py bdist_wheel for PyYAML ... done
Stored in directory: /root/.cache/pip/wheels/2c/f7/79/13f3a12cd723892437c0cfbde1230ab4d82947ff7b3839a4fc
Running setup.py bdist_wheel for dockerpty ... done
Stored in directory: /root/.cache/pip/wheels/ae/d5/14/a25cbb003bd70ffefba0fdfbd5a5c4ea4d2a11bde7736f7482
Running setup.py bdist_wheel for docopt ... done
Stored in directory: /root/.cache/pip/wheels/b2/16/5f/c33a2bb5f2dce71205f8e65cbfd05647d79d441282be31fd82
Running setup.py bdist_wheel for functools32 ... done
Stored in directory: /root/.cache/pip/wheels/3c/d0/09/cd78d0ff4d6cfecfbd730782a7815a4571cd2cd4d2ed6e69d9
Successfully built texttable backports.ssl-match-hostname PyYAML dockerpty docopt functools32
Installing collected packages: texttable, backports.ssl-match-hostname, websocket-client, ipaddress, docker-pycreds, requests, docker, functools32, jsonschema, cached-property, enum34, PyYAML, dockerpty, docopt, docker-compose
Found existing installation: backports.ssl-match-hostname 3.4.0.2
Uninstalling backports.ssl-match-hostname-3.4.0.2:
Successfully uninstalled backports.ssl-match-hostname-3.4.0.2
Successfully installed PyYAML-3.12 backports.ssl-match-hostname-3.5.0.1 cached-property-1.3.1 docke


# ln -s /usr/bin/docker-compose /usr/local/bin/



接下来介绍几个术语
#build
Usage: build [options] [SERVICE...]

Options:
--force-rm  Always remove intermediate containers.
--no-cache  Do not use cache when building the image.
--pull      Always attempt to pull a newer version of the image.
当修改dockerfile或者docker-compose时,运行docker-compose build 重建镜像。  生成镜像后,可使用docker-compose up启动

config
Usage: config [options]

Options:
-q, --quiet     只验证配置,不输出。 当配置正确时,不输出任何内容,当文件配置错误,输出错误信息。
--services      打印服务名,一行一个
验证和查看compose文件配置。
create
为服务创建容器.只是单纯的create,还需要使用start启动compose

Usage: create [options] [SERVICE...]

Options:
--force-recreate       重新创建容器,即使他的配置和镜像没有改变,不兼容--no-recreate参数
--no-recreate          如果容器已经存在,不需要重新创建. 不兼容--force-recreate参数
--no-build             不创建镜像,即使缺失.
--build                创建容器前,生成镜像.
down
Usage: down [options]

Options:
--rmi type          删除镜像,类型必须是:
'all': 删除compose文件中定义的所以镜像.
'local': 删除镜像名为空的镜像
-v, --volumes       删除卷
attached to containers.
--remove-orphans    Remove containers for services not defined in the
Compose file
停止和删除容器、网络、卷、镜像,这些内容是通过docker-compose up命令创建的.  默认值删除 容器 网络,可以通过指定 rmi volumes参数删除镜像和卷

events
Usage: events [options] [SERVICE...]

Options:
--json      输出事件日志,json格式
输出docker-compose 事件的日志,当执行docker-compose命令操作时,docker-compose even命令就会监控日志:
{
"service": "web",
"event": "create",
"container": "213cf75fc39a",
"image": "alpine:edge",
"time": "2015-11-20T18:01:03.615550",
}
exec
Usage: exec [options] SERVICE COMMAND [ARGS...]

Options:
-d                分离模式,后台运行命令.
--privileged      获取特权.
--user USER       指定运行的用户.
-T                禁用分配TTY. By default `docker-compose exec`
分配 a TTY.
--index=index     当一个服务拥有多个容器时,可通过该参数登陆到该服务下的任何服务,例如:docker-compose exec --index=1 web /bin/bash ,web服务中包含多个容器
instances of a service [default: 1]
和docker exec命令功能相同,可以通过service name登陆到容器中
e.g. docker-compose exec web sh
kill
Usage: kill [options] [SERVICE...]

Options:
-s SIGNAL         向容器发送信号. 默认是SIGKILL.
通过发送 SIGKILL 信号来强制停止服务容器。支持通过参数来指定发送的信号:
$ docker-compose kill -s SIGINT
logs
Usage: logs [options] [SERVICE...]

Options:
--no-color          单色输出,不显示其他颜.
-f, --follow        跟踪日志输出,就是可以实时查看日志
-t, --timestamps    显示时间戳
--tail              从日志的结尾显示,--tail=200
显示日志输出.
pause
Usage: pause [SERVICE...]
暂停容器服务. docker-compose pause  暂停所有服务. docker-compose pause web,之后暂停web服务的容器。
unpause
Usage: unpause [SERVICE...]
恢复容器服务. docker-compose unpause  恢复所有服务. docker-compose unpause web,之后恢复web服务的容器。
port
Usage: port [options] SERVICE PRIVATE_PORT

Options:
--protocol=proto  tcp or udp [default: tcp]
--index=index     index of the container if there are multiple
instances of a service [default: 1]
输出服务的共有端口.
# docker-compose port web 8080   -- 8080为容器内部端口
0.0.0.0:8884
ps
Usage: ps [options] [SERVICE...]

Options:
-q    只显示ID
显示容器. 默认显示name、command、state、ports
pull
Usage: pull [options] [SERVICE...]

Options:
--ignore-pull-failures  忽略pull失败的镜像,继续pull其他镜像.
pull compose文件中所指明的镜像.
push
Usage: push [options] [SERVICE...]

Options:
--ignore-push-failures  忽略错误.
push compose文件中所指明的镜像
restart
Usage: restart [options] [SERVICE...]

Options:
-t, --timeout TIMEOUT      Specify a shutdown timeout in seconds. (default: 10)
Restarts services.
rm
Usage: rm [options] [SERVICE...]

Options:
-f, --force   Don't ask to confirm removal
-v            期初加载到容器的任何匿名卷
-a, --all     Also remove one-off containers created by
docker-compose run
Removes stopped service containers. 如果服务在运行,需要先docker-compose stop 停止容器
By default, anonymous volumes attached to containers will not be removed. You can override this with -v. To list all volumes, use docker volume ls.
Any data which is not in a volume will be lost.
run
Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]

Options:
-d                   后台运行,输出容器名.
-e KEY=VAL            设置环境变量参数,可以使用多次
-u, --user=""         指定运行的用户
--no-deps             不启动link服务,只启动run的服务.
--rm                  运行后删除容器,后台运行模式除外(-d).
-p, --publish=[]      开放端口
--service-ports       compose文件中配置什么端口,就映射什么端口.
-T                    禁用TTY.
-w, --workdir=""      设置工作目录
启动web服务器,并执行bash命令.
$ docker-compose run web bash
根据compose配置文件制定的端口,映射到主机:
$ docker-compose run --service-ports web python manage.py shell
指定端口映射到主机:
$ docker-compose run --publish 8080:80 -p 2022:22 -p 127.0.0.1:2021:21 web python manage.py shell
link db容器:
$ docker-compose run db psql -h db -U docker
不linke容器,单独启动指定容器:
$ docker-compose run --no-deps web python manage.py shell
scale
Usage: scale [SERVICE=NUM...]
设置服务的个数.
$ docker-compose scale web=2 worker=3
start
Usage: start [SERVICE...]
启动服务.
stop
Usage: stop [options] [SERVICE...]

Options:
-t, --timeout TIMEOUT     关闭超时时间 (default: 10).
停止容器.
up
Usage: up [options] [SERVICE...]

Options:
-d                         后台运行,输出容器的名字.
Incompatible with --abort-on-container-exit.
--no-color                  单色输出.
--no-deps                  不启动link服务.
--force-recreate           强制重新创建compose服务,即使没有任何改变。重新创建后启动容器
Incompatible with --no-recreate.
--no-recreate               如果容器已经存在,不重新创建.
Incompatible with --force-recreate.
--no-build                 不创建重启,即使镜像不存在.
--build                    重新创建镜像,然后生成容器.
--abort-on-container-exit  任何容器停止,自动停止所有容器.
Incompatible with


下面创建一个web项目,一个nginx挂载三个web容器
docker-nginx目录作为工作目录,并在其中创建一个子目录nginx

# pwd
/root/docker-nginx
[root@yankerp docker-nginx]# mkdir nginx
[root@yankerp docker-nginx]# ll
总用量 0
drwxr-xr-x. 2 root root 6 9月  23 15:16 nginx


在/root/docker-nginx/nginx下创建nginx的主配置文件nginx.conf
在/root/docker-nginx/下创建docker-compose.yml文件

下面是创建目录的内容
nginx.conf文件内容

# pwd
/root/docker-nginx/nginx
[root@yankerp nginx]# vim nginx.conf
[root@yankerp nginx]# cat nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
worker_connections  1024;
}

http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
upstream yankerp{
server Apache1:80 weight=1;
server Apache2:80 weight=1;
server Apache3:80 weight=1;
}
server {
listen       80;
server_name  localhost;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {
root   html;
index  index.html index.htm;
proxy_pass http://yankerp; }

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1; #}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
}

# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#    listen       8000;
#    listen       somename:8080;
#    server_name  somename  alias  another.alias;

#    location / {
#        root   html;
#        index  index.html index.htm;
#    }
#}

# HTTPS server
#
#server {
#    listen       443 ssl;
#    server_name  localhost;

#    ssl_certificate      cert.pem;
#    ssl_certificate_key  cert.key;

#    ssl_session_cache    shared:SSL:1m;
#    ssl_session_timeout  5m;

#    ssl_ciphers  HIGH:!aNULL:!MD5;
#    ssl_prefer_server_ciphers  on;

#    location / {
#        root   html;
#        index  index.html index.htm;
#    }
#}

}
daemon off;


yml文件内容

[root@yankerp docker-nginx]# pwd
/root/docker-nginx
[root@yankerp docker-nginx]# ls
docker-compose.yml  nginx
[root@yankerp docker-nginx]# cat docker-compose.yml
Apache1:
image: centos:http
expose:
- 80

Apache2:
image: centos:http
expose:
- 80

Apache3:
image: centos:http
expose:
- 80

nginx:
image: centos:nginx
links:
- Apache1
- Apache2
- Apache3
ports:
- "8000:80"


配置完成后运行compose项目

在docker-nginx目录下执行docker-compose up -d启动应用

# pwd
/root/docker-nginx
[root@yankerp docker-nginx]# docker-compose up -d
Creating dockernginx_Apache2_1 ...
Creating dockernginx_Apache1_1 ...
Creating dockernginx_Apache3_1 ...
Creating dockernginx_Apache2_1
Creating dockernginx_Apache1_1
Creating dockernginx_Apache2_1 ... done
Creating dockernginx_nginx_1 ...
Creating dockernginx_nginx_1 ... done


查看容器启动情况。

# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
a7e7bed203a6        centos:nginx        "nginx"                  29 seconds ago      Up 9 seconds        0.0.0.0:8000->80/tcp   dockernginx_nginx_1
8b6704eb5f6d        centos:http         "/usr/sbin/httpd -DFO"   39 seconds ago      Up 28 seconds       80/tcp                 dockernginx_Apache3_1
fa540c849b72        centos:http         "/usr/sbin/httpd -DFO"   39 seconds ago      Up 29 seconds       80/tcp                 dockernginx_Apache1_1
50c037a51a16        centos:http         "/usr/sbin/httpd -DFO"   39 seconds ago      Up 29 seconds       80/tcp                 dockernginx_Apache2_1




希望对您有所帮助,再见
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: