目錄
前言
昨天發了一個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
參考資料及感謝
感謝資料提供者/作者