[Docker入门-2] Docker Containers 的创建和使用

更多精彩内容:http://www.codeye.top/

Dockerfile

  • Dockerfile 定义了容器内部环境,虚拟了网络、存储等资源,该环境与系统的其他部分隔离。外部访问服务资源时,Dockerfile会说明需要“复制”到哪些文件哪些环境

创建Dockerfile

vi Dockerfile

文件内容如下:

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

Dockerfile文件中包含了app.py和requirements.txt文件(说明即将进行哪些操作)

app.py文件内容

from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "<i>cannot connect to Redis, counter disabled</i>"

    html = "<h3>Hello {name}!</h3>" \
           "<b>Hostname:</b> {hostname}<br/>" \
           "<b>Visits:</b> {visits}"
    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

requirements.txt文件内容

Flask
Redis

内容如下:
在这里插入图片描述

创建一个Docker镜像

docker build --tag=friendlyhello .

在这里插入图片描述
在这里插入图片描述

运行应用

docker run -p 4000:80 friendlyhello

在这里插入图片描述
访问:http://localhost:4000/
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值