[docker-compose] image build與pull(build非dockerfile名稱)

目錄結構

當要build的image名稱不是dockerfile時,是其他名稱,且在不同路徑下,例如:

.
├── docker-compose.yml
└── my_flask
    ├── app.py
    └── dockerfile.data
  • build: 要build的指令:
    • context: 檔案路徑
    • dockerfile: 檔案名稱

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 f"Hello Container World! I have been seen {redis.get('hits').decode('utf-8')} times and my hostname is {socket.gethostname()}.\n"

dockerfile如下:

FROM python:3.9.5-slim

RUN pip install flask redis && \
    groupadd -r flask && useradd -r -g flask flask && \
    mkdir /src && \
    chown -R flask:flask /src

USER flask

COPY app.py /src/app.py

WORKDIR /src

ENV FLASK_APP=app.py REDIS_HOST=redis

EXPOSE 5000

CMD ["flask", "run", "-h", "0.0.0.0"]

docker_compose.yml檔如下:

version: "3.8"

services:
  flask-demo:
    build:
      context: ./my_flask
      dockerfile: Dockerfile.data
    image: flask_demo:latest
    environment:
      - REDIS_HOST=redis-server
    networks:
      - demo-network
    ports:
      - 8899:5000

  redis-server:
    container_name: redis-demo
    image: redis:latest
    networks:
      - demo-network

networks:
  demo-network: null

成功畫面:

docker-compose image build/pull的指令差異

當docker-compose.yml檔內同時有要從dockerfile build的image與從dockerhub pull下來時,這兩種會不同結果

docker-compose build

下方是利用docker_compose.yml檔執行的結果,只有build dockerfile,沒有redis image:

docker-compose pull

下方是從dockerhub pull redis,因為dockerfile的關係所以馬上就是done,而pull則需等待下載:

可以看到,下方使用pull,只有一個redis的image

部分基礎的命令行基本使用

  • -d: 背景執行
docker-compose up -d

若想查看log可使用下方兩個指令

  • -f :持續動態的查看
docker-compose logs
docker-compose logs -f

查看容器目前狀況:

$ docker-compose ps
         Name                        Command               State           Ports         
-----------------------------------------------------------------------------------------
my_flask_flask-demo_1     flask run -h 0.0.0.0             Up      0.0.0.0:8899->5000/tcp
my_flask_redis-server_1   docker-entrypoint.sh redis ...   Up      6379/tcp      

注意:使用docker-compose ps時,要在yml檔的目錄底下才能使用,否則無法查詢

將容器停止:

docker-compose stop

將已經停止的容器刪除:

$ docker-compose rm  
Going to remove my_flask_flask-demo_1, my_flask_redis-server_1
Are you sure? [yN] y
Removing my_flask_flask-demo_1   ... done
Removing my_flask_redis-server_1 ... done

發佈留言

內容索引