美文网首页程序员
如果你也需要重新封装Nodejs镜像

如果你也需要重新封装Nodejs镜像

作者: 77即是正义 | 来源:发表于2017-04-05 23:34 被阅读254次

因为项目需要,我需要在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"]
    

相关文章

网友评论

    本文标题:如果你也需要重新封装Nodejs镜像

    本文链接:https://www.haomeiwen.com/subject/mjwxattx.html