一般來說,自定義Nginx只需要把靜態文件放到鏡像里就可以了,不需要重寫 CMD 與 ENTRYPOINT。但是,如果的確需要在 Nginx 啟動前執行一些操作,就需要重寫 CMD 了,如果寫成下邊就樣:
FROM nginx
COPY someshell.sh /
RUN chmod +x /someshell.sh
CMD someshell.sh && nginx -g daemon off;
就會得到個錯誤 nginx: invalid option: "off"。網上很多報這種錯誤的,今天打鏡像時恰巧碰到又忘了之前的作法了,索性記錄下來,備忘以及幫助后來者。
提供兩種類似的自定義 Nginx 鏡像寫法,一種放在 Dockerfile 里執行腳本 + 啟動 Nginx,另一種是腳本里把所有的事都做完。
僅 Dockerfile 修改
FROM nginx:1.16
#省略復制前端的命令
COPY docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh
CMD /docker-entrypoint.sh && nginx -g 'daemon off;'
沒看錯,只是在 daemon off; 前后加上 單引號。docker-entrypoint.sh 名稱及內容均可自定義。
腳本中All in One
Dockerfile:
FROM nginx:1.16
#省略復制前端的命令
COPY docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh
CMD /docker-entrypoint.sh
docker-entrypoint.sh:
#!/bin/bash
#做一些操作。。。
nginx -g 'daemon off;'
總結
問題主要出在 daemon off; 對於Nginx的參數而言必須是一個整體。
