如何使用Docker容器将HTML5模式的angular2应用程序部署

如何在Docker容器中部署angular2应用程序,

目前我正在使用快递节点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 (eg 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); }); 

我的基地url

 <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 

build造

build立

docker build -t testapp:v1。

这个方法完美的工作。 但我想知道,是否有更好的方式来运行Angular 2应用程序与HTML5模式?

在Docker镜像中构buildangular度应用程序非常简单,只要您知道如何:

  1. 构build应用程序ng build --prod
  2. 添加.htaccess文件
  3. dist复制到httpd映像。
  4. 利润

使用这种方法将从您的代码中删除表示逻辑,这意味着您将不得不pipe理更less的代码并专注于应用程序本身。

示例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是在一个configuration项目已经完成的CI过程中build立的。 当然你必须在构build图像之前构build应用程序。

我这样做,因为这样,原来的打字稿代码和CSS不在网上提供,所以他们无法从网站本身。