一、概念:
通过service创建container的方式有两种:第一种是从官网拉取镜像,第二种是本地build
二:安装和实验
docker-compose 命令:
官网安装:
https://docs.docker.com/compose/install/
命令使用:
默认识别本地docker-compose.yml文件并执行(-d 代表后台执行)docker-compose up -d
指定compose文件docker-compose -f my-docker-compose.yml up-d
这里我们启动一个yaml文件:
vim docker-compose.yml
version: '3'
services:
wordpress:
image: wordpress
ports:
- 8080:80
depends_on:
- mysql
environment:
WORDPRESS_DB_HOST: mysql
WORDPRESS_DB_PASSWORD: root
networks:
- my-bridge
mysql:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: wordpress
volumes:
- mysql-data:/var/lib/mysql
networks:
- my-bridge
volumes:
mysql-data:
networks:
my-bridge:
driver: bridge
当前目录启动:
docker-compose up -d
执行会默认创建一个网络环境和container
查看镜像:
docker-compose images
查看容器:
docker-compose ps
停止容器:
docker-compose stop
运行容器:
docker-compose start
删除yml文件中的容器:
docker-compose down
进入container(名字是yml文件中的service名字):
docker-compose exec wordpress bash
docker-compose使用docker build方式启动一个容器
创建一个目录
app.py
from flask import Flask
from redis import Redis
import os
import socket
app = Flask(__name__)
redis = Redis(host=os.environ.get('REDIS_HOST', '127.0.0.1'), port=6379)
@app.route('/')
def hello():
redis.incr('hits')
return 'Hello Container World! I have been seen %s times and my hostname is %s.\n' % (redis.get('hits'),socket.gethostname())
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
Dockerfile
FROM python:2.7
LABEL maintaner="lijiahao928611@gmail.com"
COPY . /app
WORKDIR /app
RUN pip install flask redis
EXPOSE 5000
CMD [ "python", "app.py" ]
docker-compse-yml
version: "3"
services:
redis:
image: redis
web:
build:
context: .
dockerfile: Dockerfile
ports:
- 8080:5000
environment:
REDIS_HOST: redis
docker build -t .
docker-compose up -d
水平扩展和负载均衡
水平扩展:
vi docker-compse-yml
删除这两行:
docker-compose up --scale web=3 -d
实战一:测试web
app.py
from flask import Flask
from redis import Redis
import os
import socket
app = Flask(__name__)
redis = Redis(host=os.environ.get('REDIS_HOST', '127.0.0.1'), port=6379)
@app.route('/')
def hello():
redis.incr('hits')
return 'Hello Container World! I have been seen %s times and my hostname is %s.\n' % (redis.get('hits'),socket.gethostname())
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80, debug=True)
Dockerfile
FROM python:2.7
LABEL maintaner="Peng Xiao xiaoquwl@gmail.com"
COPY . /app
WORKDIR /app
RUN pip install flask redis
EXPOSE 80
CMD [ "python", "app.py" ]
docker-compose.yml
version: "3"
services:
redis:
image: redis
web:
build:
context: .
dockerfile: Dockerfile
ports: ["8080"]
environment:
REDIS_HOST: redis
lb:
image: dockercloud/haproxy
links:
- web
ports:
- 80:80
volumes:
- /var/run/docker.sock:/var/run/docker.sock
docker-compose up
docker-compose up --scale web=3 -d
测试:
发布者:LJH,转发请注明出处:https://www.ljh.cool/5354.html