【问题标题】:Dockerize your Angular NodeJS applicationDocker 化你的 Angular NodeJS 应用程序
【发布时间】:2016-04-19 22:10:12
【问题描述】:

我们有一个前端应用程序。 它是用 Angular (html + css + javascript) 编写的,需要由网络服务器 (nginx) 托管。 Angular 正在与 NodeJs 服务器进行通信,该服务器将与后端进行通信。

现在我们必须在 Docker 中运行它。

  • 我们要使用 2 个 Docker 容器:一个使用 nodejs,一个使用 nginx,让它们一起工作

那么是否可以在一个存储库中写入 2 个 dockerfile? 主要思想是为 nodejs 提供 1 个 dockerfile,它也在运行 bower install、npm install、... 看起来像这样:

# Create app directory
RUN mkdir -p /usr/src/www
WORKDIR /usr/src/www

RUN npm install -g bower
RUN npm install -g gulp

# Install app dependencies
COPY . /usr/src/www/
RUN bower install
RUN npm install
RUN gulp build

EXPOSE port
CMD [ "node", "server.js" ]

还有一个 dockerfile,我们在其中运行 nginx-webserver,但也包含一个 nginx.conf,因此它可以指向我们的 node.js-container 中的正确 /dist 文件夹 nginx 的 dockerfile 会是这样的:

# Set nginx base image
FROM nginx

# Copy custom configuration file from the current directory
COPY nginx.conf /etc/nginx/nginx.conf

nginx.conf 的一个例子

location ~* /dist {
            proxy_pass http://nodejs:port;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;

【问题讨论】:

  • 有人可以确认这是否是正确的方法吗?

标签: angularjs node.js nginx docker


【解决方案1】:

在我看来,使用 2 个 docker 容器是最好的选择,每个容器设计的单一职责值得遵循。

每个项目必须创建多个容器是很常见的:

  • 数据库
  • 后端服务器
  • 前端服务器

一种方法是为 docker 定义和每个 docker 上下文创建一个文件夹,创建一个脚本 docker_build.sh 来准备 docker 上下文(复制所有需要的工件:库、源代码等),最后构建 docker。

project_root/
|----src/
|----docker/
|----|----angular/
|----|----|-----Dockerfile
|----|----|-----docker_build.sh
|----|----nodejs/
|----|----|-----Dockerfile
|----|----|-----docker_build.sh       

docker_build.sh 示例

#!/bin/bash

# create temp directory for building
mkdir DockerBuildTempPath/

# copy files to temp directory
cp -arv Dockerfile DockerBuildTempPath/
cp -arv ../../src/ DockerBuildTempPath/
# ... etc

cd DockerBuildTempPath

#build image
docker build -t myapp .

# remove temp directory
cd ..
rm -r ./DockerBuildTempPath/

【讨论】:

  • 你在哪里存储 package.json 因为它包含 nodejs 和 angular 的依赖项。
  • package.json 与所有其他应用程序一起位于 src 目录下。 bash 脚本的想法是临时复制所有这些东西,构建 docker 映像,然后删除它们
  • 我正在和詹金斯一起做这个。 (所以替换 voor .sh)。您会建议在 jenkins 文件夹或映像本身(dockerfile)中执行 npm 安装吗?
  • 我建议在 docker 镜像中执行 npm 安装
  • 永远不要尝试在镜像中运行 npm install 或 yarn install。当涉及到扩展和创建多个容器时,您最不想要的就是在启动时下载大量数据的数百个图像。您应该始终致力于在 Docker 映像中提供最终的生产版本。来自本指南:medium.com/@DenysVuika/…
【解决方案2】:

试试 jwilder/nginx-proxy(https://github.com/jwilder/nginx-proxy)。我目前正在使用它来托管一个主要的 docker Nginx,它代理我的所有其他 docker 服务。

【讨论】:

  • 不是答案,似乎更适合作为评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 2022-10-25
  • 2018-05-20
  • 1970-01-01
  • 2021-06-18
  • 2018-12-31
  • 1970-01-01
相关资源
最近更新 更多