博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Angular和Docker Compose创建MEAN应用
阅读量:2510 次
发布时间:2019-05-11

本文共 29182 字,大约阅读时间需要 97 分钟。

###

###

Update: 30-03-2019

更新:30 - 03 - 2019

This article has been updated based on the updates to both docker and angular since this article was written. The current version of angular is 7, the updates also adds an attached docker volume to the angular client so that you don't need to run docker-compose build evey time.

自撰写本文以来,本文已基于docker和angular的更新进行了更新。 angular的当前版本为7,更新还向Angular客户端添加了一个附加的docker卷,因此您无需运行docker-compose构建通知时间。

allows us to run applications inside containers. These containers in most cases communicate with each other.

允许我们在容器内运行应用程序。 这些容器在大多数情况下会相互通信。

Docker containers wrap a piece of software in a complete filesystem that contains everything needed to run: code, runtime, system tools, system libraries – anything that can be installed on a server. This guarantees that the software will always run the same, regardless of its environment.

Docker容器将一个软件包装在一个完整的文件系统中,该文件系统包含运行所需的一切:代码,运行时,系统工具,系统库–可以安装在服务器上的任何内容。 这保证了无论其环境如何,该软件将始终运行相同的软件。

We'll build an angular app in one container, point it to an expressjs api in another container, which connects to MongoDB in another container.

我们将在一个容器中构建一个角度应用程序,将其指向另一个容器中的expressjs api,该API在另一个容器中连接到MongoDB。

If you haven't worked with Docker before, this would be a good starting point as we will explain every step covered, in some detail.

如果您以前从未使用过Docker,那么这将是一个不错的起点,因为我们将详细介绍每个步骤。

为什么使用Docker (Why Use Docker)

  1. Docker images usually include only what your application needs to run. As a result, you don't have to worry about having a whole operating system with things you will never user. This results in smaller images of your application.

    Docker映像通常仅包含您的应用程序需要运行的内容。 因此,您不必担心拥有一个永远不会使用的东西的完整操作系统。 这样可以减小应用程序的图像。
  2. Platform Indipendent - I bet you've heard of the phrase 'It worked on my machine, and doesn't work on the server'. With Docker, all either environments need to have is the Docker Engine, or the Docker Daemon, and when we have a successful build of our image, it should run anywhere.

    平台独立人士-我敢打赌您已经听说过“它在我的机器上有效,而在服务器上不起作用”这一短语。 使用Docker,所有环境都需要拥有Docker Engine或Docker Daemon,当我们成功构建映像后,它应该可以在任何地方运行。
  3. Once you have an image of your application built, you can easily share the image to anyone who wants to run your application. They need not worry about dependencies, or setting up their individual environments. All they need to have is Docker Engine installed.

    构建完应用程序的映像后,您可以轻松地将映像共享给想要运行您的应用程序的任何人。 他们不必担心依赖关系,也不必设置自己的环境。 他们所需要的只是安装了Docker Engine。
  4. Isolation - You'll see from the article that I try to separate the individual apps to become indipendent, and only point to each other. The reason behind this is that each part of our entire application should be somewhat indipendent, and scalable on it's own. Docker in this instance would make scaling these individual parts as easy as spinning up another instance of their images. This concept of building isolated, indipendenlty scalable parts of an entire system is what is called Microservices Approach.You can read more about it in

    隔离-从文章中您会看到,我试图将各个应用程序分开以使其相互独立,并且仅指向彼此。 这背后的原因是我们整个应用程序的每个部分都应该是独立的,并且可以自行扩展。 在这种情况下,Docker将使扩展这些单个部分变得像旋转其映像的另一个实例一样容易。 在整个系统中构建隔离的,独立的,可扩展的部分的概念称为微服务方法。您可以在微服务阅读有关它的更多信息。
  5. Docker images usually have tags, referring to their versions. This means you can have versioned builds of your image, enabling you to roll back to a previous version should something unexpected break.

    Docker映像通常具有引用其版本的标签。 这意味着您可以对映像的版本进行版本控制,以便在意外中断时回滚到以前的版本。

( )

You need to have docker and docker-compose installed in your setup. Instructions for installing docker in your given platform can be .

您需要在安装程序中安装docker和docker-compose。 可以在给定平台上安装docker的说明。

Instructions for installing docker-compose can be found here.

可以在此处找到有关安装docker-compose的说明。

Verify your installation by runnig

通过runnig验证安装

$ docker  -vDocker version 18.09.2, build 6247962$ docker-compose -vdocker-compose version 1.23.2, build 1110ad01$ node -vv11.12.0

Next, you need to know how to build a simple Angular app and an Express App. We'll be using the to build a simple app.

接下来,您需要了解如何构建简单的Angular应用程序和Express应用程序。 我们将使用来构建一个简单的应用程序。

( )

We'll now separately build out these three parts of our app. The approach we are going to take is building the app in our local environment, then dockerizing the app.

现在,我们将分别构建应用程序的这三个部分。 我们将采用的方法是在本地环境中构建应用程序,然后对应用程序进行docker化。

Once these are running, we'll connect the three docker containers. Note that we are only building two containers, Angular and the Express/Node API. The third container will be from a MongoDB image that we'll just pull from the .

一旦这些运行,我们将连接三个docker容器。 请注意,我们仅构建了两个容器,即Angular和Express / Node API。 第三个容器来自MongoDB映像,我们将从提取该映像。

Docker Hub is a repository for docker images. It's where we pull down official docker images such as MongoDB, NodeJs, Ubuntu, and we can also create custom images and push them to Docker Hub for other people to pull and use.

Docker Hub是Docker映像的存储库。 在这里,我们可以提取MongoDB,NodeJs,Ubuntu等官方docker映像,还可以创建自定义映像并将其推送到Docker Hub,以供其他人提取和使用。

Let's create a directory for our whole set up, we'll call it mean-docker.

让我们为整个设置创建一个目录,我们将其称为mean-docker

$mkdir mean-docker

( )

Next, we'll create an Angular app and make sure it runs in a docker container.

接下来,我们将创建一个Angular应用,并确保它在docker容器中运行。

Create a directory called angular-client inside the mean-docker directory we created above, and initialize an Angular App with the Angular CLI.

在上面创建的mean-docker目录中创建一个名为angular-client的目录,然后使用Angular CLI初始化Angular App。

We'll use npx, a tool that allows us to run CLI apps without installing them into our system. It comes preinstalled when you install ndeJS since version 5.2.0

我们将使用npx,该工具可让我们运行CLI应用程序而无需将其安装到系统中。 从5.2.0版开始安装ndeJS时,它已预装

$ npx @angular/cli new angular-client? Would you like to add Angular routing? No? Which stylesheetformat would you like to use? CSS

This scaffolds an angular app, and npm installs the app's dependencies. Our directory structure should be like this

这将搭建一个有角度的应用程序,而npm将安装该应用程序的依赖项。 我们的目录结构应该像这样

└── mean-docker    └── angular-client        ├── README.md        ├── angular.json        ├── e2e        ├── node_modules        ├── package.json        ├── package-lock.json        ├── src        ├── tsconfig.json        └── tslint.json

Running npm start, inside the angular-client directory should start the angular app at http://localhost:4200.

angular-client目录中运行npm start,应在http://localhost:4200处启动angular应用。

( )

To dockerize any app, we usually need to write a

要对任何应用进行Docker化,我们通常需要编写一个

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

Dockerfile是一个文本文档,其中包含用户可以在命令行上调用以组装映像的所有命令。

To quickly brainstorm on what our angular app needs in order to run,

为了Swift就如何运行我们的角度应用程序进行头脑风暴,

  1. We need an image with nodejs installed on it

    我们需要一个安装了nodejs的图像
  2. We could have the Angular CLI installed on the image, but the package.json file has it as a dependency, so it's not a requirement.

    我们可以在映像上安装Angular CLI,但是package.json文件将其作为依赖项,因此不是必需的。
  3. We can add our angular app into the image and install it's dependencies.

    我们可以将我们的角度应用程序添加到图像中并安装其依赖项。
  4. It needs to expose port 4200 so that we can access it from our host machine through localhost:4200.

    它需要公开端口4200,以便我们可以通过localhost:4200从主机访问它。
  5. If all these requirements are met, we can run npm start in the container, which in turn runs ng serve since it's a script in the package.json file, created from the image and our app should run.

    如果满足所有这些要求,我们可以在容器中运行npm start ,而容器又运行ng serve因为它是package.json文件中的脚本,是从映像创建的,并且我们的应用程序应该运行。

Those are the exact instructions we are going to write in our Dockerfile.

这些是我们要在Dockerfile中编写的确切说明。

mean-docker/angular-client/Dockerfile

均值 -docker /角度 - 客户端/ Dockerfile

# Create image based on the official Node 10 image from dockerhubFROM node:10# Create a directory where our app will be placedRUN mkdir -p /app# Change directory so that our commands run inside this new directoryWORKDIR /app# Copy dependency definitionsCOPY package*.json /app/# Install dependeciesRUN npm install# Get all the code needed to run the appCOPY . /app/# Expose the port the app runs inEXPOSE 4200# Serve the appCMD ["npm", "start"]

I've commented on the file to show what each instruction clearly does.

我对文件进行了评论,以显示每个指令的明确作用。

NOTE Before we build the image, if you are keen, you may have noticed that the line COPY . /app/ copies our whole directory into the container, including node_modules. To ignore this, and other files that are irrelevant to our container, we can add a .dockerignore file and list what is to be ignored. This file is usually sometimes identical to the .gitignore file.

注意在创建映像之前,如果您很热衷,您可能已经注意到COPY . /app/COPY . /app/ COPY . /app/整个目录复制到容器中,包括node_modules 。 要忽略此内容以及与容器不相关的其他文件,我们可以添加.dockerignore文件并列出要忽略的内容。 该文件通常有时与.gitignore文件相同。

Create a .dockerignore file.

创建一个.dockerignore文件。

mean-docker/angular-client/.dockerignore

均值 -docker /角度 - 客户端/.dockerignore

node_modules/

One last thing we have to do before building the image, is to ensure that the app is served from the host created by the docker image. To ensure this, go into your package.json and change the start script to.

构建映像之前,我们要做的最后一件事是确保从docker映像创建的主机上提供应用程序。 为此,请进入package.json并将start脚本更改为。

mean-docker/angular-client/package.json

均值 -docker / angular - client / package.json

{
... "scripts": {
"start": "ng serve --host 0.0.0.0", ... }, ...}

To build the image we will use docker build command. The syntax is

要构建映像,我们将使用docker build命令。 语法是

$ docker build -t
:

Make sure you are in the mean_docker/angular-client directory, then build your image.

确保您位于mean_docker/angular-client目录中,然后构建映像。

$cd angular-client$ docker build -t angular-client:dev .

-t is a shortform of --tag, and refers to the name or tag given to the image to be built. In this case the tag will be angular-client:dev.

-t--tag ,指代要构建的映像的名称或标记。 在这种情况下,标签将是angular-client:dev

The . (dot) at the end refers to current directory. Docker will look for the Dockerfile in our current directory and use it to build an image.

. 末尾的(点)表示当前目录。 Docker将在当前目录中查找Dockerfile并使用它来构建映像。

This could take a while depending on your internet connection.

这可能需要一段时间,具体取决于您的互联网连接。

Now that the image is built, we can run a container based on that image, using this syntax

现在已经构建了映像,我们可以使用以下语法在该映像的基础上运行一个容器

$ docker run -d --name
-p

The -d flag tells docker to run the container in detached mode. Meaning, it will run and get you back to your host, without going into the container.

-d标志告诉docker以detached模式运行容器。 意思是,它将运行并带您回到主机,而无需进入容器。

$ docker run -d --name angular-client -p 4200:4200 angular-client:dev8310253fe80373627b2c274c5a9de930dc7559b3dc8eef4abe4cb09aa1828a22

--name refers to the name that will be assigned to the container.

--name是指将分配给容器的名称。

-p or --port refers to which port our host machine should point to in the docker container. In this case, localhost:4200 should point to dockerhost:4200, and thus the syntax 4200:4200.

-p--port指的是我们的主机应在Docker容器中指向哪个端口。 在这种情况下, localhost:4200应该指向dockerhost:4200 ,因此语法为4200:4200

Visit localhost:4200 in your host browser should be serving the angular app from the container.

在您的主机浏览器中访问localhost:4200应该从容器中提供angular应用程序。

You can stop the container running with

您可以停止容器运行

$ docker stop angular-client

( )

We've containerized the angular app, we are now two steps away from our complete set up.

我们已经对angular应用程序进行了容器化,距离完成设置只有两个步骤。

Containerizing an express app should now be straight forward. Create a directory in the mean-docker directory called express-server.

现在,将快递应用程序容器化应该很简单。 在mean-docker目录中创建一个名为express-server目录。

$mkdir express-server

Add the following package.json file inside the app.

在应用程序内添加以下package.json文件。

mean-docker/express-server/package.json

均值 -docker / express - server / package.json

{
"name": "express-server", "version": "0.0.0", "private": true, "scripts": {
"start": "node server.js" }, "dependencies": {
"body-parser": "~1.15.2", "express": "~4.14.0" }}

Then, we'll create a simple express app inside it. Create a file server.js

然后,我们将在其中创建一个简单的Express应用。 创建一个文件server.js

$cd express-serve $ touch server.js $ mkdir routes && cd routes $ touch api.js

mean-docker/express-server/server.js

均值 -docker / express - server / server.js

// Get dependenciesconst express = require('express');const path = require('path');const http = require('http');const bodyParser = require('body-parser');// Get our API routesconst api = require('./routes/api');const app = express();// Parsers for POST dataapp.use(bodyParser.json());app.use(bodyParser.urlencoded({
extended: false }));// Set our api routesapp.use('/', api);// _Get port from environment and store in Express._**const port = process.env.PORT || '3000';app.set('port', port);**// _Create HTTP server._const server = http.createServer(app);/_* _ Listen on provided port, on all network interfaces. */server.listen(port, () => console.log(`API running on localhost:${
port}`));

mean_docker/express-server/routes/api.js

意思 _ 泊坞窗/快递 - 服务器/路由/ api.js

const express = require('express');const router = express.Router();/_ GET api listing. _/router.get('/', (req, res) => {
res.send('api works');});module.exports = router;

This is a simple express app, install the dependencies and start the app.

这是一个简单的快速应用程序,安装依赖项并启动该应用程序。

$npm install$ npm start

Going to localhost:3000 in your browser should serve the app.

在浏览器中转到localhost:3000即可投放该应用。

To run this app inside a docker container, we'll also create a Dockerfile for it. It should be pretty similar to what we already have for the angular-client.

为了在Docker容器中运行此应用程序,我们还将为其创建一个Dockerfile。 它应该与我们为angular-client已经拥有的非常相似。

mean-docker/express-server/Dockerfile

平均 - 泊坞窗/快递 - 服务器/ Dockerfile

# Create image based on the official Node 6 image from the dockerhubFROM node:6# Create a directory where our app will be placedRUN mkdir -p /usr/src/app# Change directory so that our commands run inside this new directoryWORKDIR /usr/src/app# Copy dependency definitionsCOPY package.json /usr/src/app# Install dependeciesRUN npm install# Get all the code needed to run the appCOPY . /usr/src/app# Expose the port the app runs inEXPOSE 3000# Serve the appCMD ["npm", "start"]

You can see the file is pretty much the same as the angular-client Dockerfile, except for the exposed port.

您可以看到该文件与angular-client Dockerfile几乎相同,除了公开的端口。

You could also add a .dockerignore file to ignore files we do not need.

您还可以添加.dockerignore文件来忽略我们不需要的文件。

mean-docker/express-server/.dockerignore

平均 - 泊坞窗/快递 - 服务器/ .dockerignore

node_modules/

We can then build the image and run a container based on the image with.

然后,我们可以构建图像并基于图像运行容器。

$ docker build -t express-server:dev.$ docker run -d --name express-server -p 3000:3000 express-server:dev

Going to localhost:3000 in your browser should serve the api.

在浏览器中转到localhost:3000应该可以使用该api。

Once you are done, you can stop the container with

完成后,您可以使用

$ docker stop express-server

( )

The last part of our MEAN set up, before we connect them all together is the MongoDB. Now, we can't have a Dockerfile to build a MongoDB image, because one already exists from the . We only need to know how to run it.

在将它们连接在一起之前,MEAN设置的最后一部分是MongoDB。 现在,我们无法使用Dockerfile来构建MongoDB映像,因为已经存在一个映像。 我们只需要知道如何运行它。

Assuming we had a MongoDB image already, we'd run a container based on the image with

假设我们已经有一个MongoDB映像,我们将基于该映像运行一个容器

$ docker run -d --name mongodb -p 27017:27017 mongo

The image name in this instance is mongo, the last parameter, and the container name will be mongodb.

该实例中的映像名称是mongo ,最后一个参数,而容器名称将是mongodb

Docker will check to see if you have a mongo image already downloaded, or built. If not, it will look for the image in the Dockerhub. If you run the above command, you should have mongodb instance running inside a container.

Docker将检查您是否已经下载或构建了mongo映像。 如果没有,它将在Dockerhub中查找映像。 如果运行上述命令,则应该在容器内运行mongodb实例。

To check if mongodb is running, simply go to http://localhost:27017 in you browser, and you should see this message. It looks like you are trying to access MongoDB over HTTP on the native driver port.

要检查mongodb是否正在运行,只需在浏览器中转到http://localhost:27017 ,您应该会看到此消息。 It looks like you are trying to access MongoDB over HTTP on the native driver port.

Alternatively, if you have mongo installed in your host machine, simply run mongo in the terminal. And it should run and give you the mongo shell, without any errors.

另外,如果您在主机中安装了mongo,只需在终端中运行mongo 。 它应该运行并为您提供mongo shell,而不会出现任何错误。

( )

To connect and run multiple containers with docker, we use Docker Compose.

要使用Docker连接并运行多个容器,我们使用Docker Compose。

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a Compose file to configure your application’s services. Then, using a single command, you create and start all the services from your configuration.

Compose是用于定义和运行多容器Docker应用程序的工具。 通过Compose,您可以使用Compose文件配置应用程序的服务。 然后,使用单个命令,从您的配置中创建并启动所有服务。

Docker compose is usually installed when you install docker. So to simply check if you have it installed, run

Docker compose通常在安装docker时安装。 因此,只需检查是否已安装,请运行

$ docker-compose

You should see a list of commands from docker-compose. If not, you can go through the installation

您应该看到docker-compose中的命令列表。 如果没有,您可以在进行安装

Note: Ensure that you have docker-compose version 1.6 and above by running docker-compose -v

注意 :通过运行docker-compose -v确保您具有docker-compose版本1.6及更高版本

Create a docker-compose.yml file in the root of our set up.

在设置的根目录中创建一个docker-compose.yml文件。

$touch docker-compose.yml

Our directory tree should now look like this.

现在,目录树应如下所示。

.├── angular-client├── docker-compose.yml└── express-server

Then edit the docker-compose.yml file

然后编辑docker-compose.yml文件

mean-docker/docker-compose.yml

意思是 -docker / docker - composeyml

version: '2' # specify docker-compose version# Define the services/containers to be runservices:  angular: # name of the first service    build: angular-client # specify the directory of the Dockerfile    ports:      - "4200:4200" # specify port forewarding  express: #name of the second service    build: express-server # specify the directory of the Dockerfile    ports:      - "3000:3000" #specify ports forewarding  database: # name of the third service    image: mongo # specify image to build container from    ports:      - "27017:27017" # specify port forewarding

The docker-compose.yml file is a simple configuration file telling docker compose which continers to build. That's pretty much it.

docker-compose.yml文件是一个简单的配置文件,告诉docker compose要构建的容器。 就是这样。

Now, to run containers based on the three images, simply run

现在,要基于三个图像运行容器,只需运行

$ docker-compose up

This will build the images if not already built, and run them. Once it's running, and your terminal looks something like this.

如果尚未生成映像,则将生成它们并运行它们。 一旦运行,您的终端将如下所示。

You can visit all the three apps, http://localhost:4200, http://localhost:3000 or mongodb://localhost:27017, and you'll see that all the three containers are running.

您可以访问所有三个应用程序http://localhost:4200http://localhost:3000mongodb://localhost:27017 ,您将看到所有三个容器都在运行。

( )

Finally, the fun part.

最后,有趣的部分。

Express和MongoDb (Express and MongoDb)

We now finally need to connect the three containers. We'll first create a simple CRUD feature in our api using . You can go through to get a more detailed explanation of mongoose.

现在,我们终于需要连接三个容器。 我们将首先使用在我们的api中创建一个简单的CRUD功能。 您可以以获得的更详细说明。

First of all, add mongoose to your express server package.json

首先,将猫鼬添加到快递服务器package.json

mean-docker/express-server/package.json

均值 -docker / express - server / package.json

{
"name": "express-server", "version": "0.0.0", "private": true, "scripts": {
"start": "node server.js" }, "dependencies": {
"body-parser": "~1.15.2", "express": "~4.14.0", "mongoose": "^4.7.0" }}

We need to update our api to use mongo

我们需要更新我们的API以使用mongo

mean-docker/express-server/routes/api.js

意思是 - 泊坞窗/快递 - 服务器/路由/ api.js

// Import dependenciesconst mongoose = require('mongoose');const express = require('express');const router = express.Router();// MongoDB URL from the docker-compose fileconst dbHost = 'mongodb://database/mean-docker';// Connect to mongodbmongoose.connect(dbHost);// create mongoose schemaconst userSchema = new mongoose.Schema({
name: String, age: Number});// create mongoose modelconst User = mongoose.model('User', userSchema);/_ GET api listing. _/router.get('/', (req, res) => {
res.send('api works');});/_ GET all users. _/router.get('/users', (req, res) => {
User.find({
}, (err, users) => {
if (err) res.status(500).send(error) res.status(200).json(users); });});/_ GET one users. _/router.get('/users/:id', (req, res) => {
User.findById(req.param.id, (err, users) => {
if (err) res.status(500).send(error) res.status(200).json(users); });});/_ Create a user. _/router.post('/users', (req, res) => {
let user = new User({
name: req.body.name, age: req.body.age }); user.save(error => {
if (error) res.status(500).send(error); res.status(201).json({
message: 'User created successfully' }); });});module.exports = router;

Two main differences, first of all our connection to mongo db is in the line const dbHost = 'mongodb://database/mean-docker';. This database is the same as the database service we created in the docker-compose file.

两个主要区别是,首先我们与mongo db的连接是在const dbHost = 'mongodb://database/mean-docker'; 。 该database与我们在docker-compose文件中创建的数据库服务相同。

We've also added rest routes GET /users, GET /users/:id and POST /user.

我们还添加了休息路线GET /usersGET /users/:idPOST /user

Update the docker-compose file, telling the express service to link to the database service.

更新docker-compose文件,告诉Express服务链接到数据库服务。

mean-docker/docker-compose.yml

意思是 -docker / docker - composeyml

version: '2' # specify docker-compose version# Define the services/containers to be runservices:  angular: # name of the first service    build: angular-client # specify the directory of the Dockerfile    ports:      - "4200:4200" # specify port forewarding    volumes:      - ./angular-client:/app # this will enable changes made to the angular app reflect in the container  express: #name of the second service    build: express-server # specify the directory of the Dockerfile    ports:      - "3000:3000" #specify ports forewarding    links:      - database  database: # name of the third service    image: mongo # specify image to build container from    ports:      - "27017:27017" # specify port forewarding

The links property of the docker-compose file creates a connection to the other service with the name of the service as the host name. In this case database will be the hostname. Meaning, to connect to it frrom the express service, we should use database:27017. That's why we made the dbHost equal to mongodb://database/mean-docker.

docker-compose文件的links属性创建以服务名称作为主机名的另一服务的连接。 在这种情况下, database将是主机名。 意思是,要从express服务连接到它,我们应该使用database:27017 。 这就是为什么我们使dbHost等于mongodb://database/mean-docker

Also, I've added a volumes to the angular service. This will enable changes we make to the Angular App automatically trigger recompilation in the container

另外,我还向角度服务添加了一个卷。 这将启用我们对Angular App所做的更改,从而自动触发容器中的重新编译

角度和快速 (Angular and Express)

The last part is to connect the Angular app to the express server. To do this, we'll need to make some modifications to our angular app to consume the express api.

最后一部分是将Angular应用程序连接到快递服务器。 为此,我们需要对我们的角度应用程序进行一些修改以使用Express API。

Add the Angular HTTP Client. mean-docker/angular-client/src/app.module.ts

添加Angular HTTP客户端。 均值 - 泊坞窗/角 - 客户端/src/app.module.ts

import {
BrowserModule } from '@angular/platform-browser';import {
NgModule } from '@angular/core';import {
HttpClientModule } from '@angular/common/http'; // add http client moduleimport {
AppComponent } from './app.component';@NgModule({
declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule // import http client module ], providers: [], bootstrap: [AppComponent]})export class AppModule {
}

mean-docker/angular-client/src/app/app.component.ts

均值 - 泊坞窗/角 - 客户端/src/app/app.component.ts

import {
Component, OnInit } from '@angular/core';import {
HttpClient } from '@angular/common/http';@Component({
selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements OnInit {
title = 'app works!'; // Link to our api, pointing to localhost API = 'http://localhost:3000'; // Declare empty list of people people: any[] = []; constructor(private http: HttpClient) {
} // Angular 2 Life Cycle event when component has been initialized ngOnInit() {
this.getAllPeople(); } // Add one person to the API addPerson(name, age) {
this.http.post(`${
this.API}/users`, {
name, age}) .subscribe(() => {
this.getAllPeople(); }) } // Get all users from the API getAllPeople() {
this.http.get(`${
this.API}/users`) .subscribe((people: any) => {
console.log(people) this.people = people }) }}

Angular best practices guides usually recommend separating most logic into a service/provider. We've placed all the code in the component here for brevity.

Angular最佳实践指南通常建议将大多数逻辑分为服务/提供者。 为了简洁起见,我们将所有代码都放在了组件中。

We've imported the OnInit interface, to call events when the component is initialized, then added a two methods AddPerson and getAllPeople, that call the API.

我们已经导入了OnInit接口,以在初始化组件时调用事件,然后添加了两个调用API的方法AddPersongetAllPeople

Notice that this time round, our API is pointing to localhost. This is because while the angular 2 app will be running inside the container, it's served to the browser. And the browser is the one that makes request. It will thus make a request to the exposed express API. As a result, we don't need to link Angular and Express in the docker-compose.yml file.

请注意,这一次,我们的API指向localhost 。 这是因为虽然angular 2应用程序将在容器内运行,但已将其提供给浏览器。 浏览器是发出请求的浏览器。 因此,它将向公开的Express API发出请求。 因此,我们不需要在docker-compose.yml文件中链接Angular和Express。

Next, we need to make some changes to the template. I first added bootstrap via cdn to the index.html

接下来,我们需要对模板进行一些更改。 我首先通过CDN将引导程序添加到index.html

mean-docker/angular-client/src/app/index.html

均值 - 泊坞窗/角 - 客户端/src/app/index.html

  
Angular Client
Loading...

Then update the app.component.html template

然后更新app.component.html模板

mean-docker/angular-client/src/app/app.component.html

均值 - 泊坞窗/角 - 客户端/src/app/app.component.html

Add new person

People

{
{person.name}} {
{person.age}}

The above template shows the components properties and bindings. We are almost done.

上面的模板显示了组件的属性和绑定。 我们快完成了。

Since we've made changes to our code, we need to do a build for our Docker Compose

由于我们已经更改了代码,因此需要为Docker Compose做一个构建

$ docker-compose up --build

The --build flag tells docker compose that we've made changes and it needs to do a clean build of our images.

--build标志告诉docker compose我们已经进行了更改,它需要对映像进行干净的构建。

Once this is done, go to localhost:4200 in your browser,

完成此操作后,在浏览器中转到localhost:4200

We are getting a No 'Access-Control-Allow-Origin' error. To quickly fix this, we need to enable Cross-Origin in our express app. We'll do this with a simple middleware.

我们收到No 'Access-Control-Allow-Origin'错误。 为了快速解决此问题,我们需要在Express应用程序中启用Cross-Origin。 我们将使用一个简单的中间件来实现。

mean-docker/express-server/server.js

均值 -docker / express - server / server.js

// Code commented out for brevity// Parsers for POST dataapp.use(bodyParser.json());app.use(bodyParser.urlencoded({
extended: false }));// Cross Origin middlewareapp.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") next()})// Set our api routesapp.use('/', api);// Code commented out for brevity

We can now run docker-compose again with the build flag. You should be in the mean-docker directory

现在,我们可以使用build标志再次运行docker-compose。 你应该在均值 - 泊坞窗目录

$ docker-compose up --build

Going to localhost:4200 on the browser.

在浏览器上转到localhost:4200

( )

EDIT: **- ** I added an attached volume to the docker-compose file, and we now no longer need to rebuild the service every time we make a change.

编辑:**- **我向docker-compose文件添加了一个附加卷,现在我们不再需要每次进行更改时都重新构建服务。

I bet you've learned a thing or two about MEAN or docker and docker-compose.

我敢打赌,您已经了解了有关MEAN或docker和docker-compose的一两件事。

The problem with our set up however is that any time we make changes to either the angular app, or the express api, we need to run docker-compose up --build.

但是,设置的问题在于,每当我们对angular应用或express api进行更改时,都需要运行docker-compose up --build

This can get tidious or even boring over time. We'll look at this in the another article.

随着时间的流逝,这可能会变得乏味甚至无聊。 我们将在另一篇文章中对此进行研究。

翻译自:

转载地址:http://nzywd.baihongyu.com/

你可能感兴趣的文章
C#——winform
查看>>
CSS3 transform制作的漂亮的滚动式导航
查看>>
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
SQL 通用数据类型
查看>>
UVALive 6145 Version Controlled IDE(可持久化treap、rope)
查看>>
mysql 将两个有主键的表合并到一起
查看>>
底部导航栏-----FragmentTabHost
查看>>
在linux中安装jdk以及tomcat并shell脚本关闭启动的进程
查看>>
apk,task,android:process与android:sharedUserId的区别
查看>>
MySQL 同主机不同数据库之间的复制
查看>>
matplotlib函数理解
查看>>
前端实现文件的断点续传
查看>>
转:spring4.0之二:@Configuration的使用
查看>>
【Android开发】交互界面布局详解
查看>>
状态机编程思想(1):括号内外字符串统计
查看>>
K-Means聚类和EM算法复习总结
查看>>