因為項目需要,我需要在32bit的debian系統上重新封裝一個Nodejs的Docker鏡像。踩了一天的坑,這里記錄一下。
Dockerfile
Dockerfile的簡介與語法這里就不贅述了,如果有需要可以查看使用Dockerfile構建Docker鏡像 、Dockerfile指令總結。
我這里介紹一下我遇到的問題:
- 首先因為在Dockerfile中使用
RUN <command>
,實際是在容器當中運行/bin/sh -c
指令,但是在Ubuntu、Debian等Linux系統當中,默認的終端是dash。dash的功能非常弱,比如我再使用source
等命令時均不支持。所以最好還是使用RUN['/bin/bash', '-c', '<command>']
,這樣會使用bash當做終端執行命令。 -
Nodejs的系統變量問題:在version 0.6.x的Ubuntu及對應的Debian系統當中,最好把nodejs的路徑做一次軟連接
ln -s /usr/bin/nodejs /usr/bin/node
,不然有時候會報錯找不到node。 -
bower的使用問題:因為進入容器時默認是root用戶進入,所以在使用bower的時候出讓你添加
--allow-root option
使用,但是我使用的過程當中會報錯 bower ENOTFOUND Package option not found,這個時候需要去掉option,直接使用--allow-root
,并且bower需要git環境。
源碼分析
-
基礎鏡像引入
FROM 32bit/debian
-
作者署名
MAINTAINER ShowMeCode
-
修改debian的鏡像,加快構建速度
RUN echo 'deb http://mirrors.163.com/debian jessie main non-free contrib'> /etc/apt/sources.list
RUN echo 'deb http://mirrors.163.com/debian jessie-proposed-updates main contrib non-free'>> /etc/apt/sources.list
RUN echo 'deb http://mirrors.163.com/debian-security jessie/updates main contrib non-free'>> /etc/apt/sources.list
RUN echo 'deb http://security.debian.org jessie/updates main contrib non-free'>> /etc/apt/sources.list
RUN apt-get update
```
-
安裝nvm,使用nvm安裝node
使用nvm安裝的話比編譯安裝要快的多,使用apt-get安裝的版本非常低RUN apt-get -y install curl tar # 配置環境變量 ENV NVM_DIR /usr/local/nvm ENV NODE_VERSION 6.2.2 ENV WORK_DIR /ClabServer # 下載和配置Node.js環境 # 這些命令一定要寫在一起, 否則`nvm`命令會找不到 RUN curl https://raw.githubusercontent.com/creationix/nvm/v0.24.0/install.sh >> install.sh RUN ["/bin/bash", "-c", "sh install.sh && source /usr/local/nvm/nvm.sh && nvm install v6.2.2 && nvm use v6.2.2 && nvm alias default v6.2.2"]
-
到這邊其實Nodejs的debian鏡像就制作好了,也可以繼續配置自己的服務。
# 將項目復制到鏡像中 WORKDIR ~ COPY . /ClabServer WORKDIR /ClabServer # 安裝項目依賴 RUN mkdir logs RUN ["/bin/bash", "-c", "npm --registry=https://registry.npm.taobao.org install"] RUN ["/bin/bash", "-c", "npm --registry=https://registry.npm.taobao.org install -g --save bower"] RUN ["/bin/bash", "-c", "ln -s /usr/bin/nodejs /usr/bin/node"] RUN ["/bin/bash", "-c", "bower install bootstrap --allow-root"]
-
最后啟動項目
# 暴露端口 EXPOSE 3000:3000 # 啟動項目 CMD ["nodemon", "app.js"]