0

如何使用 docker 容器部署 angular2 应用程序,

目前我正在使用带有 express 的 Node js 来提供我的应用程序内容,

index.js

 // set server port. SERVER_PORT varibale will come from Dockerfile
var port = process.env.SERVER_PORT;
if (!port) {
    port = 3000;
}
// set internal communication url
global.internalURL = "http://localhost:" + port;

var path = require('path');
var express = require('express');
var app = express();
var bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(function(req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,access_token');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

var router = express.Router(express);
app.use("/testapp", router);

router.use(express.static(path.join(__dirname, 'dist')));

// Catch all other routes and return the index file
router.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

var server = app.listen(port, function() {
    console.log("server on " + port);
});

我的基本网址

<base href="/testapp/">

我的 Docker 文件

FROM node
COPY ./package-deploy.json /package.json
COPY ./index.js /index.js
RUN npm install pm2 -g
COPY ./dist /dist
RUN npm install --only=production
ENV SERVER_PORT 80
EXPOSE 80
CMD pm2-docker index.js

建造

构建

docker build -t testapp:v1 。

这种方法非常有效。但我想知道,有没有更好的方法以 HTML5 模式运行 Angular 2 应用程序?

4

1 回答 1

1

一旦你知道如何在 docker 镜像中构建一个 Angular 应用程序就非常简单了:

  1. 构建应用程序ng build --prod
  2. 添加.htaccess文件
  3. 复制disthttpd图像。
  4. 利润

使用此方法将从您的代码中删除快速逻辑,这意味着您将不得不管理更少的代码并专注于应用程序本身。

示例Dockerfile

FROM httpd:2.4

COPY ./dist /usr/local/apache2/htdocs

COPY ./.htaccess /usr/local/apache2/htdocs

.htaccess您需要在应用程序的根目录中拥有的文件:

<IfModule mod_rewrite.c>
  Options Indexes FollowSymLinks
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

如果需要,请随时查找有关该项目的更多详细信息。

编辑:

我链接到您的 Dockerfile 是在一个 CI 过程中构建的,其中应用程序构建已经完成。当然,您必须在构建映像之前构建应用程序。

我这样做是因为这样,原始打字稿代码和 css 不会在网络上提供,因此它们无法从网站本身访问。

于 2017-05-16T14:17:56.233 回答