Docker部署SayHello(FastAPI)

前言

昨天發了一個SayHello FastAPI版本,今天部署上自己的服務器了
體驗地址: http://49.232.203.244:9001/message.html

服務部署

前置條件:以下在centos7.5 雲服務器實驗通過

yum -y install git	# 安裝git
curl -sSL https://get.daocloud.io/docker | sh	# 安裝docker

git clone https://gitee.com/zy7y/sayhello

git clone https://github.com/zy7y/sayhello

上面兩個命令選一個執行就可了

部署後端

1. 進入到sayhello目錄

cd sayhello

2. 編寫API的Dockerfile(如果有請之直接構建鏡像- 在下一步)

在sayhello目錄下新建如下Dockerfile

FROM python:3.7
COPY . /app
WORKDIR ./app
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
EXPOSE 80
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

簡單說下上面內容做了什麼事情,不一定正確加了些個人理解

FROM python:3.7		# 拉取基礎鏡像python3.7,本機已有該鏡像就會使用該鏡像,沒有就去遠端倉庫拉取,速度慢就需要換下源地址,百度即可(這裏應該就是拉下鏡像後弄成了個容器)
COPY . /app		# 將當前所在目錄下所有文件 複製到 容器裏面 /app 目錄下
WORKDIR ./app	# 指定工作目錄,我的理解是後面執行的命令 都相當於在這個目錄下執行了,根目錄的形式吧
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/	# 這步是在容器裏面執行 pip 安裝依賴
EXPOSE 80	# 將容器中80 端口開放
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]	# 容器運行時將執行 uvicorn main:app --host 0.0.0.0 --port 80 啓動服務

3. 構建鏡像

docker build -t sayhello .

4. 運行容器

會自動執行dockerfile裏面的CMD命令

docker run -d --name sayhello-fastapi -p 8000:80 sayhello

5. 訪問IP:8000/message,得到如下頁面

部署前端

先確認message.html中的baseURL是不是後端服務的IP地址(127.0.0.1 不行)

1. 進入到sayhello/static目錄

cd sayhello/static/

2. 編寫Dockerfile文件(如果有請直接進入第三步)

FROM nginx:1.15.2-alpine
COPY . /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

3. 構建鏡像

docker build -t sayhello-front .

4. 啓動容器

docker run -d --name sayhello-front-9000 -p 9001:80 sayhello-front

5. 訪問IP:9001/message.html

參考資料及感謝

感謝資料提供者/作者

  1. https://aqzt.com/bubble/6513.html
  2. https://www.cnblogs.com/tian874540961/p/11916832.html
  3. https://www.runoob.com/docker/docker-dockerfile.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章