Add reference architecture docs

Signed-off-by: Usha Mandya <usha.mandya@docker.com>
This commit is contained in:
Usha Mandya 2021-01-11 19:03:03 +00:00
parent 1a3a9d1195
commit ba395bed07
25 changed files with 1427 additions and 19 deletions

View File

@ -47,18 +47,46 @@ guides:
path: /get-started/09_image_best/
- title: "Part 10: What next?"
path: /get-started/11_what_next/
- sectiontitle: Laanguage-specific guides (New)
section:
- path: /language/
title: Overview
- sectiontitle: Node.js
section:
- title: "Overview"
path: /language/nodejs/
- title: "Build images"
path: /language/nodejs/build-images/
- title: "Run containers"
path: /language/nodejs/run-containers/
- title: "Develop your app"
path: /language/nodejs/develop/
- title: "Run your tests"
path: /language/nodejs/run-tests/
- title: "Configure CI/CD"
path: /language/nodejs/configure-ci-cd/
- title: "Deploy your app"
path: /language/nodejs/deploy/
- sectiontitle: Python
section:
- title: "Overview"
path: /language/python/
- title: "Build images"
path: /language/python/build-images/
- title: "Run containers"
path: /language/python/run-containers/
- title: "Develop your app"
path: /language/python/develop/
- title: "Configure CI/CD"
path: /language/python/configure-ci-cd/
- sectiontitle: Java
section:
- title: "Overview"
path: /language/java/
- sectiontitle: Develop with Docker
section:
- path: /develop/
title: Overview
- sectiontitle: Node.js
section:
- title: "Build images"
path: /get-started/nodejs/build-images/
- title: "Run containers"
path: /get-started/nodejs/run-containers/
- title: "Develop"
path: /get-started/nodejs/develop/
- path: /develop/dev-best-practices/
title: Best practices
- sectiontitle: Build images

View File

@ -85,10 +85,10 @@
</a>
</div>
<div class="col-xs-12 col-sm-6 col-lg-4 card-holder">
<a class="card whats-new" href="/release-notes/">
<h5 class="title">What's new?</h5>
<a class="card guides" href="/language/">
<h5 class="title">Language-specific guides</h5>
<p>
Learn about the cool new features, updates, and bug fixes.
Learn how to containerize language-specific applications using Docker.
</p>
</a>
</div>
@ -125,6 +125,7 @@
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-6"><a href="/language/">Containerize language-specific apps using Docker</a></div>
<div class="col-xs-12 col-md-6"><a href="/engine/reference/builder/">Write a Dockerfile</a></div>
<div class="col-xs-12 col-md-6"><a href="/network/">Manage container networking</a></div>
<div class="col-xs-12 col-md-6"><a href="/compose/compose-file/">Write a Docker Compose file</a></div>
@ -134,8 +135,6 @@
<div class="col-xs-12 col-md-6"><a href="/get-started/02_our_app/">Build and run an image</a></div>
<div class="col-xs-12 col-md-6"><a href="/config/labels-custom-metadata/">Manage Docker objects</a></div>
<div class="col-xs-12 col-md-6"><a href="/develop/develop-images/multistage-build/">Use multi-stage builds</a></div>
<div class="col-xs-12 col-md-6"><a href="/get-started/kube-deploy/">Scale apps using Kubernetes</a></div>
<div class="col-xs-12 col-md-6"><a href="/engine/reference/commandline/run/">Run a command in a container</a></div>
<div class="col-xs-12 col-md-6"><a href="/get-started/swarm-deploy/">Scale apps using Swarm</a></div>
</div>
</div>
@ -236,7 +235,7 @@
<p class="only-mac"><a href="/docker-for-mac/install/">Install Docker Desktop on Mac</a></p>
<p><a href="/desktop/dashboard/">Docker Desktop Dashboard</a></p>
<p class="only-win"><a href="/docker-for-windows/kubernetes/">Deploy on Kubernetes</a></p>
<p class="only-win"><a href="/docker-for-windows/release-notes/">Stable Release notes</a></p>
<p class="only-win"><a href="/docker-for-windows/release-notes/">Release notes</a></p>
<p class="only-win"><a href="/docker-for-windows/troubleshoot/">Logs and troubleshooting</a></p>
<p class="only-mac"><a href="/docker-for-mac/networking/">Networking features in Docker Desktop</a></p>
</div>
@ -350,8 +349,8 @@
<div class="col-xs-12 col-md-6">
<h2 class="title">Develop with Docker</h2>
<p>Learn how to develop language-specific apps using Docker.</p>
<p><a href="/language/nodejs/" target="_blank" rel="noopener">Containerize Node.js app using Docker</a></p>
<p><a href="https://github.com/docker/labs/tree/master/developer-tools/java/" target="_blank" rel="noopener">Docker for Java developers</a></p>
<p><a href="https://github.com/docker/labs/tree/master/developer-tools/nodejs/porting/" target="_blank" rel="noopener">Port a node.js app to Docker</a></p>
<p><a href="https://github.com/docker/labs/tree/master/developer-tools/ruby" target="_blank" rel="noopener">Ruby on Rails app on Docker</a></p>
<p><a href="/engine/examples/dotnetcore/">Dockerize a .Net Core application</a></p>
<p><a href="/compose/aspnet-mssql-compose/" target="_blank" rel="noopener">Dockerize an ASP.NET Core application with SQL Server on Linux</a></p>

View File

@ -66,12 +66,11 @@ code {
width: 100%;
background: $bg-component;
img {
width: 70px;
height: 70px;
}
.component-icon {
margin: 0 auto;
width: 70px;
display: flex;
justify-content: center;
}
h2 {
font-size: 22px;

View File

@ -58,7 +58,11 @@ redirect_from:
Welcome! We are excited that you want to learn Docker.
This page contains step-by-step instructions on how to get started with Docker. We also recommend the video walkthrough from DockerCon 2020.
This page contains step-by-step instructions on how to get started with Docker.
If you are looking for information on how to containerize an application using your favorite language, see [Language-specific getting started guides](/language).
We also recommend the video walkthrough from DockerCon 2020.
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/iqqDU2crIEQ?start=30" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

BIN
language/images/java.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
language/images/nodejs.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
language/images/python.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

51
language/index.md Normal file
View File

@ -0,0 +1,51 @@
---
description: :Language-specific getting started guides overview
keywords: guides, docker, language, node, java, python
title: Overview
toc_min: 1
toc_max: 2
---
This page contains information on how to develop language-specific applications using Docker.
The language-specific getting started guides contain best practices and guidelines that explain how to create a new Dockerfile in your preferred language, what to include in the Docker image, how to develop and run your Docker image, set up a CI/CD pipeline, and finally provides information on how to push the application you've developed to the cloud.
In addition to the language-specific modules, Docker documentation also provides guidelines to build and efficiently manage your development environment. You can find information on the best practices for writing Dockerfiles, building and managing images efficiently, gaining performance improvements by building images using BuildKit, etc. You can also find specific instructions on how to keep your images small, and how to persist application data, how to use multi-stage builds, etc.
For more information, refer to the following topics:
* [Best practices for writing Dockerfiles](/develop/develop-images/dockerfile_best-practices/)
* [Docker development best practices](/develop/dev-best-practices/)
* [Build images with BuildKit](/develop-images/build_enhancements/)
* [Manage images](/develop/develop-images/image_management/)
## Language-specific getting started guides
Learn how to set up your Docker environment and start containerizing your applications. Choose a language below to get started.
<div class="component-container">
<!--start row-->
<div class="row" style="display: flex; align-items: center">
<div class="col-sm-12 col-md-12 col-lg-4 block" style="margin: 0 10px;box-shadow: 0 3px 6px #0b214a17, 0 -2px 2px #0b214a08; height: 100px; display: flex; align-items: center">
<div class="component-icon">
<a href="/language/nodejs/"><img src="/language/images/nodejs.png" alt="Develop with Node"></a>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-4 block" style="margin: 0 10px;box-shadow: 0 3px 6px #0b214a17, 0 -2px 2px #0b214a08; height: 100px; display: flex; align-items: center">
<a href="/language/python/">
<div class="component-icon">
<img src="/language/images/python.png" alt="Develop with Python">
</div>
</a>
</div>
<div class="col-sm-12 col-md-12 col-lg-4 block" style="margin: 0 10px;box-shadow: 0 3px 6px #0b214a17, 0 -2px 2px #0b214a08; height: 100px; display: flex; align-items: center">
<div class="component-icon">
<a href="/language/java/"><img src="/language/images/java.png" alt="Develop with Java"></a>
</div>
</div>
</div>
</div>
To request a guide for other languages, create an issue in the [Docker Docs github repository](https://github.com/docker/docker.github.io/issues/new?title=[Language%20specific%guides%20request]){:target="_blank" rel="noopener" class="_"}.
<br />

20
language/java/index.md Normal file
View File

@ -0,0 +1,20 @@
---
description: Containerize Java apps using Docker
keywords: Docker, getting started, java, language
title: What will you learn in this module?
toc_min: 1
toc_max: 2
---
> ### Coming soon
>
> Thanks for your interest in learning how to containerize a Java application. We are actively writing this guide. Watch this space!
Meanwhile, here's an outline of the tasks we are planning to cover. Here's an outline of what we'd like to cover. Using the Java getting started guide, you'll learn how to:
* Create a new Dockerfile which contains instructions required to build a Java image
* Build an image and run the newly built image as a container
* Set up a local development environment to connect a database to the container, and use Docker Compose to run the application.
* Configure a CI/CD pipeline for your application using GitHub Actions.
<br />

View File

@ -0,0 +1,254 @@
---
title: "Build your Node image"
keywords: containers, images, node.js, node, dockerfiles, node, coding, build, push, run
description: Learn how to build your first Docker image by writing a Dockerfile
redirect_from:
- /get-started/nodejs/build-images/
---
{% include_relative nav.html selected="1" %}
## Prerequisites
Work through the orientation and setup in Get started [Part 1](/get-started/) to understand Docker concepts.
## Overview
Now that we have a good overview of containers and the Docker platform, lets take a look at building our first image. An image includes everything you need to run an application - the code or binary, runtime, dependencies, and any other file system objects required.
To complete this tutorial, you need the following:
- Node.js version 12.18 or later. [Download Node.js](https://nodejs.org/en/){: target="_blank" rel="noopener" class="_"}
- Docker running locally: Follow the instructions to [download and install Docker](https://docs.docker.com/desktop/).
- An IDE or a text editor to edit files. We recommend using Visual Studio Code.
## Sample application
Lets create a simple Node.js application that we can use as our example. Create a directory on your local machine named `node-docker` and follow the steps below to create a simple REST API.
```shell
$ cd [path to your node-docker directory]
$ npm init -y
$ npm install ronin-server ronin-mocks
$ touch server.js
```
Now, lets add some code to handle our REST requests. Well use a mock server so we can focus on Dockerizing the application.
Open this working directory in your IDE and add the following code into the `server.js` file.
```node
const ronin = require( 'ronin-server' )
const mocks = require( 'ronin-mocks' )
const server = ronin.server()
server.use( '/', mocks.server( server.Router(), false, true ) )
server.start()
```
The mocking server is called `Ronin.js` and will listen on port 8000 by default. You can make POST requests to the root (/) endpoint and any JSON structure you send to the server will be saved in memory. You can also send GET requests to the same endpoint and receive an array of JSON objects that you have previously POSTed.
## Test application
Lets start our application and make sure its running properly. Open your terminal and navigate to your working directory you created.
```shell
$ node server.js
```
To test that the application is working properly, well first POST some JSON to the API and then make a GET request to see that the data has been saved. Open a new terminal and run the following curl commands:
```shell
$ curl --request POST \
--url http://localhost:8000/test \
--header 'content-type: application/json' \
--data '{
"msg": "testing"
}'
{"code":"success","payload":[{"msg":"testing","id":"31f23305-f5d0-4b4f-a16f-6f4c8ec93cf1","createDate":"2020-08-28T21:53:07.157Z"}]}
$ curl http://localhost:8000/test
{"code":"success","meta":{"total":1,"count":1},"payload":[{"msg":"testing","id":"31f23305-f5d0-4b4f-a16f-6f4c8ec93cf1","createDate":"2020-08-28T21:53:07.157Z"}]}
```
Switch back to the terminal where our server is running. You should now see the following requests in the server logs.
```node
2020-XX-31T16:35:08:4260 INFO: POST /test
2020-XX-31T16:35:21:3560 INFO: GET /test
```
## Create a Dockerfile for Node.js
A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. When we tell Docker to build our image by executing the `docker build` command, Docker reads these instructions and executes them one by one and creates a Docker image as a result.
Lets walk through the process of creating a Dockerfile for our application. In the root of your working directory, create a file named `Dockerfile` and open this file in your text editor.
> **Note**
>
> The name of the Dockerfile is not important but the default filename for many commands is simply `Dockerfile`. So, well use that as our filename throughout this series.
The first thing we need to do is to add a line in our Dockerfile that tells Docker what base image we would like to use for our application.
```dockerfile
FROM node:12.18.1
```
Docker images can be inherited from other images. Therefore, instead of creating our own base image, well use the official Node.js image that already has all the tools and packages that we need to run a Node.js application. You can think of this in the same way you would think about class inheritance in object oriented programming. For example, if we were able to create Docker images in JavaScript, we might write something like the following.
`class MyImage extends NodeBaseImage {}`
This would create a class called `MyImage` that inherited functionality from the base class `NodeBaseImage`.
In the same way, when we use the `FROM` command, we tell Docker to include in our image all the functionality from the `node:12.18.1` image.
> **Note**
>
> If you want to learn more about creating your own base images, see [Creating base images](https://docs.docker.com/develop/develop-images/baseimages/).
The `NODE_ENV` environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set `NODE_ENV` to `production`.
```dockerfile
ENV NODE_ENV=production
```
To make things easier when running the rest of our commands, lets create a working directory. This instructs Docker to use this path as the default location for all subsequent commands. This way we do not have to type out full file paths but can use relative paths based on the working directory.
```dockerfile
WORKDIR /app
```
Usually the very first thing you do once youve downloaded a project written in Node.js is to install npm packages. This will ensure that your application has all its dependencies installed into the `node_modules` directory where the Node runtime will be able to find them.
Before we can run `npm install`, we need to get our `package.json` and `package-lock.json` files into our images. We use the `COPY` command to do this. The `COPY` command takes two parameters. The first parameter tells Docker what file(s) you would like to copy into the image. The second parameter tells Docker where you want that file(s) to be copied to. Well copy the `package.json` and `package-lock.json` file into our working directory `/app`.
```dockerfile
COPY ["package.json", "package-lock.json*", "./"]
```
Once we have our `package.json` files inside the image, we can use the `RUN` command to execute the command npm install. This works exactly the same as if we were running npm install locally on our machine, but this time these Node modules will be installed into the `node_modules` directory inside our image.
```dockerfile
RUN npm install --production
```
At this point, we have an image that is based on node version 12.18.1 and we have installed our dependencies. The next thing we need to do is to add our source code into the image. Well use the COPY command just like we did with our `package.json` files above.
```dockerfile
COPY . .
```
The COPY command takes all the files located in the current directory and copies them into the image. Now, all we have to do is to tell Docker what command we want to run when our image is run inside of a container. We do this with the `CMD` command.
```dockerfile
CMD [ "node", "server.js" ]
```
Here's the complete Dockerfile.
```dockerfile
FROM node:12.18.1
ENV NODE_ENV=production
WORKDIR /app
COPY ["package.json", "package-lock.json*", "./"]
RUN npm install --production
COPY . .
CMD [ "node", "server.js" ]
```
## Build image
Now that weve created our Dockerfile, lets build our image. To do this, we use the `docker build` command. The `docker build` command builds Docker images from a Dockerfile and a “context”. A builds context is the set of files located in the specified PATH or URL. The Docker build process can access any of the files located in the context.
The build command optionally takes a `--tag` flag. The tag is used to set the name of the image and an optional tag in the format `name:tag`. Well leave off the optional “tag” for now to help simplify things. If you do not pass a tag, Docker will use “latest” as its default tag. Youll see this in the last line of the build output.
Lets build our first Docker image.
```shell
$ docker build --tag node-docker .
```
```shell
Sending build context to Docker daemon 82.94kB
Step 1/7 : FROM node:12.18.1
---> f5be1883c8e0
Step 2/7 : WORKDIR /code
...
Successfully built e03018e56163
Successfully tagged node-docker:latest
Viewing Local Images
To see a list of images we have on our local machine, we have two options. One is to use the CLI and the other is to use Docker Desktop. Since we are currently working in the terminal lets take a look at listing images with the CLI.
```
To list images, simply run the `images` command.
```shell
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
node-docker latest 3809733582bc About a minute ago 945MB
node 12.18.1 f5be1883c8e0 2 months ago 918MB
```
You should see at least two images listed. One for the base image `node:12.18.1` and the other for our image we just build `node-docker:latest`.
## Tag images
An image name is made up of slash-separated name components. Name components may contain lowercase letters, digits and separators. A separator is defined as a period, one or two underscores, or one or more dashes. A name component may not start or end with a separator.
An image is made up of a manifest and a list of layers. In simple terms, a “tag” points to a combination of these artifacts. You can have multiple tags for an image. Lets create a second tag for the image we built and take a look at its layers.
To create a new tag for the image we built above, run the following command.
```shell
$ docker tag node-docker:latest node-docker:v1.0.0
```
The Docker tag command creates a new tag for an image. It does not create a new image. The tag points to the same image and is just another way to reference the image.
Now run the `docker images` command to see a list of our local images.
```
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
node-docker latest 3809733582bc 24 minutes ago 945MB
node-docker v1.0.0 3809733582bc 24 minutes ago 945MB
node 12.18.1 f5be1883c8e0 2 months ago 918MB
```
You can see that we have two images that start with `node-docker`. We know they are the same image because if you look at the IMAGE ID column, you can see that the values are the same for the two images.
Lets remove the tag that we just created. To do this, well use the rmi command. The rmi command stands for “remove image”.
```shell
$ docker rmi node-docker:v1.0.0
Untagged: node-docker:v1.0.0
```
Notice that the response from Docker tells us that the image has not been removed but only “untagged”. Verify this by running the images command.
```shell
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
node-docker latest 3809733582bc 32 minutes ago 945MB
node 12.18.1 f5be1883c8e0 2 months ago 918MB
```
Our image that was tagged with `:v1.0.0` has been removed but we still have the `node-docker:latest` tag available on our machine.
## Next steps
In this module, we took a look at setting up our example Node application that we will use for the rest of the tutorial. We also created a Dockerfile that we used to build our Docker image. Then, we took a look at tagging our images and removing images. In the next module, well take a look at how to:
[Run your image as a container](run-containers.md){: .button .outline-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs ](https://github.com/docker/docker.github.io/issues/new?title=[Node.js%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

View File

@ -0,0 +1,244 @@
---
title: "Configure CI/CD for your application"
keywords: CI/CD, GitHub Actions, NodeJS, local, development
description: Learn how to develop your application locally.
---
{% include_relative nav.html selected="5" %}
This page guides you through the process of setting up a GitHub Action CI/CD pipeline with Docker containers. Before setting up a new pipeline, we recommend that you take a look at [Ben's blog](https://www.docker.com/blog/best-practices-for-using-docker-hub-for-ci-cd/){:target="_blank" rel="noopener" class="_"} on CI/CD best practices .
This guide contains instructions on how to:
1. Use a sample Docker project as an example to configure GitHub Actions
2. Set up the GitHub Actions workflow
3. Optimize your workflow to reduce the number of pull requests and the total build time, and finally,
4. Push only specific versions to Docker Hub.
## Set up a Docker project
Lets get started. This guide uses a simple Docker project as an example. The [SimpleWhaleDemo](https://github.com/usha-mandya/SimpleWhaleDemo){:target="_blank" rel="noopener" class="_"} repository contains an Ngnix alpine image. You can either clone this repository, or use your own Docker project.
![SimpleWhaleDemo](../../ci-cd/images/simplewhaledemo.png){:width="500px"}
Before we start, ensure you can access [Docker Hub](https://hub.docker.com/) from any workflows you create. To do this:
1. Add your Docker ID as a secret to GitHub. Navigate to your GitHub repository and click **Settings** > **Secrets** > **New secret**.
2. Create a new secret with the name `DOCKER_HUB_USERNAME` and your Docker ID as value.
3. Create a new Personal Access Token (PAT). To create a new token, go to [Docker Hub Settings](https://hub.docker.com/settings/security) and then click **New Access Token**.
4. Lets call this token **simplewhaleci**.
![New access token](../../ci-cd/images/github-access-token.png){:width="500px"}
5. Now, add this Personal Access Token (PAT) as a second secret into the GitHub secrets UI with the name `DOCKER_HUB_ACCESS_TOKEN`.
![GitHub Secrets](../../ci-cd/images/github-secrets.png){:width="500px"}
## Set up the GitHub Actions workflow
In the previous section, we created a PAT and added it to GitHub to ensure we can access Docker Hub from any workflow. Now, lets set up our GitHub Actions workflow to build and store our images in Hub. We can achieve this by creating two Docker actions:
1. The first action enables us to log in to Docker Hub using the secrets we stored in the GitHub Repository.
2. The second one is the build and push action.
In this example, let us set the push flag to `true` as we also want to push. Well then add a tag to specify to always go to the latest version. Lastly, well echo the image digest to see what was pushed.
To set up the workflow:
1. Go to your repository in GitHub and then click **Actions** > **New workflow**.
2. Click **set up a workflow yourself** and add the following content:
First, we will name this workflow:
```yaml
name: CI to Docker Hub
```
Then, we will choose when we run this workflow. In our example, we are going to do it for every push against the main branch of our project:
```yaml
on:
push:
branches: [ main ]
```
Now, we need to specify what we actually want to happen within our action (what jobs), we are going to add our build one and select that it runs on the latest Ubuntu instances available:
```yaml
jobs:
build:
runs-on: ubuntu-latest
```
Now, we can add the steps required. The first one checks-out our repository under `$GITHUB_WORKSPACE`, so our workflow can access it. The second is to use our PAT and username to log into Docker Hub. The third is the Builder, the action uses BuildKit under the hood through a simple Buildx action which we will also setup
{% raw %}
```yaml
steps:
- name: Check Out Repo
uses: actions/checkout@v2
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
context: ./
file: ./Dockerfile
push: true
tags: ushamandya/simplewhale:latest
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
```
{% endraw %}
Now, let the workflow run for the first time and then tweak the Dockerfile to make sure the CI is running and pushing the new image changes:
![CI to Docker Hub](../../ci-cd/images/ci-to-hub.png){:width="500px"}
## Optimizing the workflow
Next, lets look at how we can optimize the GitHub Actions workflow through build cache. This has two main advantages:
1. Build cache reduces the build time as it will not have to re-download all of the images, and
2. It also reduces the number of pulls we complete against Docker Hub. We need to make use of GitHub cache to make use of this.
Let us set up a Builder with a build cache. First, we need to set up cache for the builder. In this example, let us add the path and keys to store this under using GitHub cache for this.
{% raw %}
```yaml
- name: Cache Docker layers
uses: actions/cache@v2
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
```
{% endraw %}
And lastly, after adding the builder and build cache snippets to the top of the Actions file, we need to add some extra attributes to the build and push step. This involves:
Setting up the builder to use the output of the buildx step, and then
Using the cache we set up earlier for it to store to and to retrieve
{% raw %}
```yaml
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
context: ./
file: ./Dockerfile
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ushamandya/simplewhale:latest
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}
```
{% endraw %}
Now, run the workflow again and verify that it uses the build cache.
## Push tagged versions to Docker Hub
Earlier, we learnt how to set up a GitHub Actions workflow to a Docker project, how to optimize the workflow by setting up a builder with build cache. Lets now look at how we can improve it further. We can do this by adding the ability to have tagged versions behave differently to all commits to master. This means, only specific versions are pushed, instead of every commit updating the latest version on Docker Hub.
You can consider this approach to have your commits go to a local registry to then use in nightly tests. By doing this, you can always test what is latest while reserving your tagged versions for release to Docker Hub.
This involves two steps:
1. Modifying the GitHub workflow to only push commits with specific tags to Docker Hub
2. Setting up a GitHub Actions file to store the latest commit as an image in the GitHub registry
First, let us modify our existing GitHub workflow to only push to Hub if theres a particular tag. For example:
{% raw %}
```yaml
on:
push:
tags:
- "v*.*.*"
```
{% endraw %}
This ensures that the main CI will only trigger if we tag our commits with `V.n.n.n.` Lets test this. For example, run the following command:
```bash
git tag -a v1.0.2
git push origin v1.0.2
```
Now, go to GitHub and check your Actions
![Push tagged version](../../ci-cd/images/push-tagged-version.png){:width="500px"}
Now, lets set up a second GitHub action file to store our latest commit as an image in the GitHub registry. You may want to do this to:
1. Run your nightly tests or recurring tests, or
2. To share work in progress images with colleagues.
Lets clone our previous GitHub action and add back in our previous logic for all pushes. This will mean we have two workflow files, our previous one and our new one we will now work on.
Next, change your Docker Hub login to a GitHub container registry login:
{% raw %}
```yaml
if: github.event_name != 'pull_request'
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GHCR_TOKEN }}
```
{% endraw %}
Remember to change how the image is tagged. The following example keeps latest as the only tag. However, you can add any logic to this if you prefer:
{% raw %}
```yaml
tags: ghcr.io/${{ github.repository_owner }}/simplewhale:latest
```
{% endraw %}
![Update tagged images](../../ci-cd/images/ghcr-logic.png){:width="500px"}
Now, we will have two different flows: one for our changes to master, and one for our pull requests. Next, we need to modify what we had before to ensure we are pushing our PRs to the GitHub registry rather than to Docker Hub.
## Next steps
In this module, you have learnt how to set up GitHub Actions workflow to an existing Docker project, optimize your workflow to improve build times and reduce the number of pull requests, and finally, we learnt how to push only specific versions to Docker Hub. You can also set up nightly tests against the latest tag, test each PR, or do something more elegant with the tags we are using and make use of the Git tag for the same tag in our image.
You can also consider deploying your application to the cloud. For detailed instructions, see:
[Deploying Docker containers on Azure](/cloud/aci-integration/){: .button .outline-btn}
[Deploying Docker containers on ECS](/cloud/ecs-integration.md){: .button .outline-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs ](https://github.com/docker/docker.github.io/issues/new?title=[Node.js%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

29
language/nodejs/deploy.md Normal file
View File

@ -0,0 +1,29 @@
---
title: "Configure CI/CD for your application"
keywords: CI/CD, GitHub Actions, NodeJS, local, development
description: Learn how to develop your application locally.
---
{% include_relative nav.html selected="6" %}
Now, that we have configured a CI/CD pipleline, let's look at how we can deploy the application to cloud. Docker supports deploying containers on Azure ACI and AWS ECS.
## Docker and ACI
The Docker Azure Integration enables developers to use native Docker commands to run applications in Azure Container Instances (ACI) when building cloud-native applications. The new experience provides a tight integration between Docker Desktop and Microsoft Azure allowing developers to quickly run applications using the Docker CLI or VS Code extension, to switch seamlessly from local development to cloud deployment.
For detailed instructions, see [Deploying Docker containers on Azure](/cloud/aci-integration/).
## Docker and ECS
The Docker ECS Integration enables developers to use native Docker commands in Docker Compose CLI to run applications in Amazon EC2 Container Service (ECS) when building cloud-native applications.
The integration between Docker and Amazon ECS allows developers to use the Docker Compose CLI to set up an AWS context in one Docker command, allowing you to switch from a local context to a cloud context and run applications quickly and easily simplify multi-container application development on Amazon ECS using Compose files.
For detailed instructions, see [Deploying Docker containers on ECS](/cloud/ecs-integration.md).
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs ](https://github.com/docker/docker.github.io/issues/new?title=[Node.js%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

219
language/nodejs/develop.md Normal file
View File

@ -0,0 +1,219 @@
---
title: "Use containers for development"
keywords: get started, NodeJS, local, development
description: Learn how to develop your application locally.
redirect_from:
- /get-started/nodejs/develop/
---
{% include_relative nav.html selected="3" %}
## Prerequisites
Work through the steps to build an image and run it as a containerized application in [Run your image as a container](run-containers.md).
## Introduction
In this module, well walk through setting up a local development environment for the application we built in the previous modules. Well use Docker to build our images and Docker Compose to make everything a whole lot easier.
## Local database and containers
First, well take a look at running a database in a container and how we use volumes and networking to persist our data and allow our application to talk with the database. Then well pull everything together into a compose file which will allow us to setup and run a local development environment with one command. Finally, well take a look at connecting a debugger to our application running inside a container.
Instead of downloading MongoDB, installing, configuring and then running the Mongo database as a service, we can use the Docker Official Image for MongoDB and run it in a container.
Before we run MongoDB in a container, we want to create a couple of volumes that Docker can manage to store our persistent data and configuration. Let's use the managed volumes feature that docker provides instead of using bind mounts. You can read all about volumes in our documentation.
Lets create our volumes now. Well create one for the data and one for configuration of MongoDB.
```shell
$ docker volume create mongodb
$ docker volume create mongodb_config
```
Now well create a network that our application and database will use to talk with each other. The network is called a user-defined bridge network and gives us a nice DNS lookup service which we can use when creating our connection string.
```shell
$ docker network create mongodb
```
Now we can run MongoDB in a container and attach to the volumes and network we created above. Docker will pull the image from Hub and run it for you locally.
```shell
$ docker run -it --rm -d -v mongodb:/data/db \
-v mongodb_config:/data/configdb -p 27017:27017 \
--network mongodb \
--name mongodb \
mongo
```
Okay, now that we have a running mongodb, lets update `server.js` to use a the MongoDB and not an in-memory data store.
```javascript
const ronin = require( 'ronin-server' )
const mocks = require( 'ronin-mocks' )
const database = require( 'ronin-database' )
const server = ronin.server()
database.connect( process.env.CONNECTIONSTRING )
server.use( '/', mocks.server( server.Router(), false, false ) )
server.start()
```
Weve add the ronin-database module and we updated the code to connect to the database and set the in-memory flag to false. We now need to rebuild our image so it contains our changes.
First lets add the ronin-database module to our application using npm.
```shell
$ npm install ronin-database
```
Now we can build our image.
```shell
$ docker build --tag node-docker .
```
Now, lets run our container. But this time well need to set the `CONNECTIONSTRING` environment variable so our application knows what connection string to use to access the database. Well do this right in the `docker run` command.
```shell
$ docker run \
-it --rm -d \
--network mongodb \
--name rest-server \
-p 8000:8000 \
-e CONNECTIONSTRING=mongodb://mongodb:27017/yoda_notes \
node-docker
```
Lets test that our application is connected to the database and is able to add a note.
```shell
$ curl --request POST \
--url http://localhost:8000/notes \
--header 'content-type: application/json' \
--data '{
"name": "this is a note",
"text": "this is a note that I wanted to take while I was working on writing a blog post.",
"owner": "peter"
}'
```
You should receive the following json back from our service.
```json
{"code":"success","payload":{"_id":"5efd0a1552cd422b59d4f994","name":"this is a note","text":"this is a note that I wanted to take while I was working on writing a blog post.","owner":"peter","createDate":"2020-07-01T22:11:33.256Z"}}
```
## Use Compose to develop locally
In this section, well create a Compose file to start our node-docker and the MongoDB with one command. Well also set up the Compose file to start the node-docker in debug mode so that we can connect a debugger to the running node process.
Open the notes-service in your IDE or text editor and create a new file named `docker-compose.dev.yml`. Copy and paste the below commands into the file.
```yaml
version: '3.8'
services:
notes:
build:
context: .
ports:
- 8080:8080
- 9229:9229
environment:
- SERVER_PORT=8080
- CONNECTIONSTRING=mongodb://mongo:27017/notes
volumes:
- ./:/code
command: npm run debug
mongo:
image: mongo:4.2.8
ports:
- 27017:27017
volumes:
- mongodb:/data/db
- mongodb_config:/data/configdb
volumes:
mongodb:
mongodb_config:
```
This Compose file is super convenient as we do not have to type all the parameters to pass to the `docker run` command. We can declaratively do that in the Compose file.
We are exposing port 9229 so that we can attach a debugger. We are also mapping our local source code into the running container so that we can make changes in our text editor and have those changes picked up in the container.
One other really cool feature of using a Compose file, is that we have service resolution set up to use the service names. So we are now able to use `“mongo”` in our connection string. The reason we use mongo is because that is what we have named our mongo service in the Compose file as.
Lets start our application and confirm that it is running properly.
```shell
$ docker-compose -f docker-compose.dev.yml up --build
```
We pass the `--build` flag so Docker will compile our image and then starts it.
If all goes will you should see something similar:
![node-compile](images/node-compile.png){:width="800px"}
Now lets test our API endpoint. Run the following curl command:
```shell
$ curl --request GET --url http://localhost:8080/services/m/notes
```
You should receive the following response:
```json
{"code":"success","meta":{"total":0,"count":0},"payload":[]}
```
## Connect a debugger
Well use the debugger that comes with the Chrome browser. Open Chrome on your machine and then type the following into the address bar.
`about:inspect`
It opens the following screen.
![Chrome-inspect](images/chrome-inspect.png){:width="800px"}
Click the **Open dedicated DevTools for Node** link. This opens the DevTools that are connected to the running Node.js process inside our container.
Lets change the source code and then set a breakpoint.
Add the following code to the server.js file on line 19 and save the file.
```node
server.use( '/foo', (req, res) => {
return res.json({ "foo": "bar" })
})
```
If you take a look at the terminal where our Compose application is running, youll see that nodemon noticed the changes and reloaded our application.
![nodemon](images/nodemon.png){:width="800px"}
Navigate back to the Chrome DevTools and set a breakpoint on line 20 and then run the following curl command to trigger the breakpoint.
```shell
$ curl --request GET --url http://localhost:8080/foo
```
You should have seen the code break on line 20 and now you are able to use the debugger just like you would normally. You can inspect and watch variables, set conditional breakpoints, view stack traces, etc.
## Next steps
In this module, we took a look at creating a general development image that we can use pretty much like our normal command line. We also set up our Compose file to map our source code into the running container and exposed the debugging port.
In the next module, well take a look at how to run unit tests in Docker. See:
[Run your tests](run-tests.md){: .button .outline-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs ](https://github.com/docker/docker.github.io/issues/new?title=[Node.js%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 853 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

24
language/nodejs/index.md Normal file
View File

@ -0,0 +1,24 @@
---
description: Containerize Node.js apps using Docker
keywords: Docker, getting started, node, node.js, language
title: What will you learn in this module?
toc_min: 1
toc_max: 2
---
The Node.js getting started guide teaches you how to create a containerized Node.js application using Docker. In this guide, youll learn how to:
* Create a simple Node.js application
* Create a new Dockerfile which contains instructions required to build a Node.js image
* Run the newly built image as a container
* Set up a local development environment to connect a database to the container
* Use Docker Compose to run the Node.js application
* Configure a CI/CD pipeline for your application using GitHub Actions.
After completing the Node.js getting started modules, you should be able to containerize your own Node.js application based on the examples and instructions provided in this guide.
Let's get started!
[Build your Node.js image](build-images.md){: .button .outline-btn}
<br />

8
language/nodejs/nav.html Normal file
View File

@ -0,0 +1,8 @@
<ul class="pagination">
<li {% if include.selected=="1"%}class="active"{% endif %}><a href="/language/nodejs/build-images/">Build images</a></li>
<li {% if include.selected=="2"%}class="active"{% endif %}><a href="/language/nodejs/run-containers/">Run your image as a container</a></li>
<li {% if include.selected=="3"%}class="active"{% endif %}><a href="/language/nodejs/develop/">Use containers for development</a></li>
<li {% if include.selected=="4"%}class="active"{% endif %}><a href="/language/nodejs/run-tests/">Run your tests</a></li>
<li {% if include.selected=="5"%}class="active"{% endif %}><a href="/language/nodejs/configure-ci-cd/">Configure CI/CD</a></li>
<li {% if include.selected=="6"%}class="active"{% endif %}><a href="/language/nodejs/deploy/">Deploy your app</a></li>
</ul>

View File

@ -0,0 +1,208 @@
---
title: "Run your image as a container"
keywords: get started, Node JS, run, container,
description: Learn how to run the image as a container.
redirect_from:
- /get-started/nodejs/run-containers/
---
{% include_relative nav.html selected="2" %}
## Prerequisites
Work through the steps to build a Node JS image in [Build your Node image](build-images.md).
## Overview
In the previous module we created our sample application and then we created a Dockerfile that we used to create an image. We created our image using the command `docker build`. Now that we have an image, we can run that image and see if our application is running correctly.
A container is a normal operating system process except that this process is isolated and has its own file system, its own networking, and its own isolated process tree separate from the host.
To run an image inside of a container, we use the `docker run` command. The `docker run` command requires one parameter and that is the image name. Lets start our image and make sure it is running correctly. Execute the following command in your terminal.
```shell
$ docker run node-docker
```
When you run this command, youll notice that you were not returned to the command prompt. This is because our application is a REST server and will run in a loop waiting for incoming requests without return control back to the OS until we stop the container.
Lets make a GET request to the server using the curl command.
```shell
$ curl --request POST \
--url http://localhost:8000/test \
--header 'content-type: application/json' \
--data '{
"msg": "testing"
}'
curl: (7) Failed to connect to localhost port 8000: Connection refused
```
Our curl command failed because the connection to our server was refused. Meaning that we were not able to connect to localhost on port 8000. This is expected because our container is run in isolation which includes networking. Lets stop the container and restart with port 8000 published on our local network.
To stop the container, press ctrl-c. This will return you to the terminal prompt.
To publish a port for our container, well use the `--publish` flag (`-p` for short) on the docker run command. The format of the `--publish` command is `[host port]:[container port]`. So if we wanted to expose port 8000 inside the container to port 3000 outside the container, we would pass 3000:8000 to the --publish flag.
Start the container and expose port 8000 to port 8000 on the host.
```shell
$ docker run --publish 8000:8000 node-docker
```
Now lets rerun the curl command from above.
```shell
$ curl --request POST \
--url http://localhost:8000/test \
--header 'content-type: application/json' \
--data '{
"msg": "testing"
}'
{"code":"success","payload":[{"msg":"testing","id":"dc0e2c2b-793d-433c-8645-b3a553ea26de","createDate":"2020-09-01T17:36:09.897Z"}]}
```
Success! We were able to connect to the application running inside of our container on port 8000. Switch back to the terminal where your container is running and you should see the POST request logged to the console.
`2020-09-01T17:36:09:8770 INFO: POST /test`
Press ctrl-c to stop the container.
## Run in detached mode
This is great so far, but our sample application is a web server and we should not have to have our terminal connected to the container. Docker can run your container in detached mode or in the background. To do this, we can use the `--detach` or `-d` for short. Docker will start your container the same as before but this time will “detach” from the container and return you to the terminal prompt.
```shell
$ docker run -d -p 8000:8000 node-docker
ce02b3179f0f10085db9edfccd731101868f58631bdf918ca490ff6fd223a93b
```
Docker started our container in the background and printed the Container ID on the terminal.
Again, lets make sure that our container is running properly. Run the same curl command from above.
```shell
$ curl --request POST \
--url http://localhost:8000/test \
--header 'content-type: application/json' \
--data '{
"msg": "testing"
}'
{"code":"success","payload":[{"msg":"testing","id":"dc0e2c2b-793d-433c-8645-b3a553ea26de","createDate":"2020-09-01T17:36:09.897Z"}]}
```
## List containers
Since we ran our container in the background, how do we know if our container is running or what other containers are running on our machine? Well, we can run the `docker ps` command. Just like on Linux, to see a list of processes on your machine we would run the ps command. In the same spirit, we can run the `docker ps` command which will show us a list of containers running on our machine.
```
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ce02b3179f0f node-docker "docker-entrypoint.s…" 6 minutes ago Up 6 minutes 0.0.0.0:8000->8000/tcp wonderful_kalam
```
The `ps` command tells a bunch of stuff about our running containers. We can see the Container ID, The image running inside the container, the command that was used to start the container, when it was created, the status, ports that exposed and the name of the container.
You are probably wondering where the name of our container is coming from. Since we didnt provide a name for the container when we started it, Docker generated a random name. Well fix this in a minute but first we need to stop the container. To stop the container, run the `docker stop` command which does just that, stops the container. You will need to pass the name of the container or you can use the container id.
```shell
$ docker stop wonderful_kalam
wonderful_kalam
```
Now rerun the `docker ps` command to see a list of running containers.
```shell
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
```
## Stop, start, and name containers
Docker containers can be started, stopped and restarted. When we stop a container, it is not removed but the status is changed to stopped and the process inside of the container is stopped. When we ran the `docker ps` command, the default output is to only show running containers. If we pass the `--all` or `-a` for short, we will see all containers on our system whether they are stopped or started.
```shell
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ce02b3179f0f node-docker "docker-entrypoint.s…" 16 minutes ago Exited (0) 5 minutes ago wonderful_kalam
ec45285c456d node-docker "docker-entrypoint.s…" 28 minutes ago Exited (0) 20 minutes ago agitated_moser
fb7a41809e5d node-docker "docker-entrypoint.s…" 37 minutes ago Exited (0) 36 minutes ago goofy_khayyam
```
If youve been following along, you should see several containers listed. These are containers that we started and stopped but have not been removed.
Lets restart the container that we just stopped. Locate the name of the container we just stopped and replace the name of the container below in the restart command.
```shell
$ docker restart wonderful_kalam
```
Now, list all the containers again using the ps command.
```shell
$ docker ps --all
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ce02b3179f0f node-docker "docker-entrypoint.s…" 19 minutes ago Up 8 seconds 0.0.0.0:8000->8000/tcp wonderful_kalam
ec45285c456d node-docker "docker-entrypoint.s…" 31 minutes ago Exited (0) 23 minutes ago agitated_moser
fb7a41809e5d node-docker "docker-entrypoint.s…" 40 minutes ago Exited (0) 39 minutes ago goofy_khayyam
```
Notice that the container we just restarted has been started in detached mode and has port 8000 exposed. Also, observe the status of the container is “Up X seconds”. When you restart a container, it will be started with the same flags or commands that it was originally started with.
Lets stop and remove all of our containers and take a look at fixing the random naming issue.
Stop the container we just started. Find the name of your running container and replace the name in the command below with the name of the container on your system.
```shell
$ docker stop wonderful_kalam
wonderful_kalam
```
Now that all of our containers are stopped, lets remove them. When a container is removed, it is no longer running nor is it in the stopped status. However, the process inside the container has been stopped and the metadata for the container has been removed.
```shell
$ docker ps --all
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ce02b3179f0f node-docker "docker-entrypoint.s…" 19 minutes ago Up 8 seconds 0.0.0.0:8000->8000/tcp wonderful_kalam
ec45285c456d node-docker "docker-entrypoint.s…" 31 minutes ago Exited (0) 23 minutes ago agitated_moser
fb7a41809e5d node-docker "docker-entrypoint.s…" 40 minutes ago Exited (0) 39 minutes ago goofy_khayyam
```
To remove a container, simple run the `docker rm` command passing the container name. You can pass multiple container names to the command in one command.
Again, make sure you replace the containers names in the below command with the container names from your system.
```shell
$ docker rm wonderful_kalam agitated_moser goofy_khayyam
wonderful_kalam
agitated_moser
goofy_khayyam
```
Run the `docker ps --all` command again to see that all containers are gone.
Now lets address the pesky random name issue. Standard practice is to name your containers for the simple reason that it is easier to identify what is running in the container and what application or service it is associated with. Just like good naming conventions for variables in your code makes it simpler to read. So goes naming your containers.
To name a container, we just need to pass the `--name` flag to the run command.
```shell
$ docker run -d -p 8000:8000 --name rest-server node-docker
1aa5d46418a68705c81782a58456a4ccdb56a309cb5e6bd399478d01eaa5cdda
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1aa5d46418a6 node-docker "docker-entrypoint.s…" 3 seconds ago Up 3 seconds 0.0.0.0:8000->8000/tcp rest-server
```
Now, we can easily identify our container based on the name.
## Next steps
In this module, we took a look at running containers, publishing ports, and running containers in detached mode. We also took a look at managing containers by starting, stopping, and restarting them. We also looked at naming our containers so they are more easily identifiable. In the next module, well learn how to run a database in a container and connect it to our application. See:
[How to develop your application](develop.md){: .button .outline-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs ](https://github.com/docker/docker.github.io/issues/new?title=[Node.js%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

View File

@ -0,0 +1,255 @@
---
title: "Run your Tests using Node.js and Mocha frameworks"
keywords: Node.js, build, Mocha, test
description: How to Build and Run your Tests using Node.js and Mocha frameworks
---
{% include_relative nav.html selected="4" %}
Testing is an essential part of modern software development. Testing can mean a lot of things to different development teams. There are unit tests, integration tests and end-to-end testing. In this guide we take a look at running your unit tests in Docker.
## Sample application
Well use a fairly simple node.js application for this guide. To follow along, clone the following github repository.
```shell
$ git clone [ADD APPLICATION URL]
```
Our sample application uses an open source framework called Ronin.js for building simple REST services. It also has a mocks server that will accept JSON and return the same JSON when you send a GET request.
So, for example, if we POST a JSON data structure to the endpoint /services/users and then perform a POST request to the same URI, we will receive the JSON which we first posted.
### Running locally and testing the application
Now that we have our sample application locally, lets build our Docker image and make sure everything is running properly. Run the following commands to build and then run your Docker image in a container.
```shell
$ docker build -t node-docker .
$ docker run -it --rm --name app -p 8080:80 node-docker
```
Now lets test our application by POSTing a JSON payload and then make an HTTP GET request to make sure our JSON was saved correctly.
```
$ curl --request POST \
--url http://localhost:8080/services/test \
--header 'content-type: application/json' \
--data '{
"msg": "testing"
}'
```
Now, perform a GET request to the same endpoint to make sure our JSON payload was saved and retrieved correctly. The “id” and “createDate” will be different for you.
```shell
$ curl http://localhost:8080/services/test
{"code":"success","payload":[{"msg":"testing","id":"e88acedb-203d-4a7d-8269-1df6c1377512","createDate":"2020-10-11T23:21:16.378Z"}]}
```
## Refactor Dockerfile to run tests
Okay, now that we know our application is running properly, lets try and run our tests inside of the container. Well use the same docker run command we used above but this time, well override the CMD that is inside of our container with npm run test. This will invoke the command that is in the package.json file under the “script” section. See below.
```shell
{
...
"scripts": {
"test": "mocha ./**/*.js",
"start": "nodemon server.js"
},
...
}
```
Below is the Docker command to start the container and run tests:
```shell
$ docker run -it --rm --name app -p 8080:80 node-docker npm run test
> node-docker@0.1.0 test /code
> mocha ./**/*.js
sh: 1: mocha: not found
```
As you can see, we received an error. This error is telling us that the mocha executable could not be found. Lets take a look at the Dockerfile.
```dockerfile
FROM node:14.15.4
WORKDIR /code
COPY package.json package.json
COPY package-lock.json package-lock.json
RUN npm ci --production
COPY . .
CMD [ "node", "server.js" ]
```
The error is occurring because we are passing the `--production` flag to the npm ci command when it installs our dependencies. This tells npm to not install packages that are located under the "devDependencies" section in the package.json file. Therefore mocha will not be installed inside the image and will not be found when we try to run it.
Since we want to follow best practices and not include anything inside the container that we do not need to run our application we cant just remove the `--production` flag. We have a couple of options to fix this. One option is to create a second Dockerfile that would only be used to run tests. This has a couple of problems. The primary being keeping two Dockerfiles up-to-date. The second option is to use multi-stage builds. We can create a stage for production and one for testing. This is our preferred solution.
### Multi-stage Dockerfile for testing
Below is a multi-stage Dockerfile tha we will use to build our production image and our test image. Add the highlighted lines to your Dockerfile.
```dockerfile
FROM node:14.15.4 as base
WORKDIR /code
COPY package.json package.json
COPY package-lock.json package-lock.json
FROM base as test
RUN npm ci
COPY . .
CMD [ "npm", "run", "test" ]
FROM base as prod
RUN npm ci --production
COPY . .
CMD [ "node", "server.js" ]
```
We first add a label to the `FROM node:14.15.4` statement. This allows us to refer to this build stage in other build stages. Next we add a new build stage labeled test. We will use this stage for running our tests.
Now lets rebuild our image and run our tests. We will run the same docker build command as above but this time we will add the `--target test` flag so that we specifically run the test build stage.
```shell
$ docker build -t node-docker --target test .
[+] Building 0.7s (11/11) FINISHED
...
=> => writing image sha256:049b37303e3355f...9b8a954f
=> => naming to docker.io/library/node-docker
```
Now that our test image is built, we can run it in a container and see if our tests pass.
```shell
$ docker run -it --rm --name app -p 8080:80 node-docker
> node-docker@0.1.0 test /code
> mocha ./**/*.js
Calculator
adding
✓ should return 4 when adding 2 + 2
✓ should return 0 when adding zeros
subtracting
✓ should return 4 when subtracting 4 from 8
✓ should return 0 when subtracting 8 from 8
4 passing (11ms)
```
Ive truncated the build output but you can see that the mocha test runner completed and all our tests passed.
This is great but at the moment we have to run two docker commands to build and run our tests. We can improve this slightly by using a RUN statement instead of the CMD statement in the test stage. The CMD statement is not executed during the building of the image but is executed when you run the image in a container. While with the RUN statement, our tests will be run during the building of the image and stop the build when they fail.
Update your Dockerfile with the highlighted line below.
```dockerfile
FROM node:14.15.4 as base
WORKDIR /code
COPY package.json package.json
COPY package-lock.json package-lock.json
FROM base as test
RUN npm ci
COPY . .
RUN npm run test
FROM base as prod
RUN npm ci --production
COPY . .
CMD [ "node", "server.js" ]
```
Now to run our tests, we just need to run the docker build command as above.
```dockerfile
$ docker build -t node-docker --target test .
[+] Building 1.2s (13/13) FINISHED
...
=> CACHED [base 2/4] WORKDIR /code
=> CACHED [base 3/4] COPY package.json package.json
=> CACHED [base 4/4] COPY package-lock.json package-lock.json
=> CACHED [test 1/3] RUN npm ci
=> CACHED [test 2/3] COPY . .
=> CACHED [test 3/3] RUN npm run test
=> exporting to image
=> => exporting layers
=> => writing image sha256:bcedeeb7d9dd13d...18ca0a05034ed4dd4
```
Ive truncated the output again for simplicity but you can see that our tests are run and passed. Lets break one of the tests and observe the output when our tests fail.
Open the util/math.js file and change line 12 to the following.
```shell
11 function subtract( num1, num2 ) {
12 return num2 - num1
13 }
```
Now, run the same docker build command from above and observe that the build fails and the failing testing information is printed to the console.
```shell
$ docker build -t node-docker --target test .
> [test 3/3] RUN npm run test:
#11 0.509
#11 0.509 > node-docker@0.1.0 test /code
#11 0.509 > mocha ./**/*.js
#11 0.509
#11 0.811
#11 0.813
#11 0.815 Calculator
#11 0.815 adding
#11 0.817 ✓ should return 4 when adding 2 + 2
#11 0.818 ✓ should return 0 when adding zeros
#11 0.818 subtracting
#11 0.822 1) should return 4 when subtracting 4 from 8
#11 0.823 ✓ should return 0 when subtracting 8 from 8
#11 0.823
#11 0.824
#11 0.824 3 passing (14ms)
#11 0.824 1 failing
#11 0.824
#11 0.827 1) Calculator
#11 0.827 subtracting
#11 0.827 should return 4 when subtracting 4 from 8:
#11 0.827
#11 0.827 AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
#11 0.827
#11 0.827 -4 !== 4
#11 0.827
#11 0.827 + expected - actual
#11 0.827
#11 0.827 --4
#11 0.827 +4
#11 0.827
#11 0.827 at Context.<anonymous> (util/math.test.js:18:14)
#11 0.827 at processImmediate (internal/timers.js:461:21)
...
executor failed running [/bin/sh -c npm run test]: exit code: 1
```
## Next steps
In this module, we took a look at creating a general development image that we can use pretty much like our normal command line. We also set up our Compose file to map our source code into the running container and exposed the debugging port.
In the next module, well take a look at how to set up a CI/CD pipeline using GitHub Actions. See:
[Configure CI/CD](configure-ci-cd.md){: .button .outline-btn}
## Feedback
Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the [Docker Docs ](https://github.com/docker/docker.github.io/issues/new?title=[Node.js%20docs%20feedback]){:target="_blank" rel="noopener" class="_"} GitHub repository. Alternatively, [create a PR](https://github.com/docker/docker.github.io/pulls){:target="_blank" rel="noopener" class="_"} to suggest updates.
<br />

View File

@ -0,0 +1,11 @@
---
title: "Build your Python image"
keywords: python, build, images, dockerfile
description: Learn how to build your first Docker image by writing a Dockerfile
---
> ### Coming soon
>
> Thanks for your interest in learning how to containerize a Python application. We are actively working on this topic. Watch this space!
<br />

View File

@ -0,0 +1,11 @@
---
title: "Configure CI/CD for your application"
keywords: python, CI/CD, local, development
description: Learn how to Configure CI/CD for your application
---
> ### Coming soon
>
> Thanks for your interest in learning how to containerize a Python application. We are actively working on this topic. Watch this space!
<br />

View File

@ -0,0 +1,11 @@
---
title: "Use containers for development"
keywords: python, local, development, run,
description: Learn how to develop your application locally.
---
> ### Coming soon
>
> Thanks for your interest in learning how to containerize a Python application. We are actively working on this topic. Watch this space!
<br />

22
language/python/index.md Normal file
View File

@ -0,0 +1,22 @@
---
description: Containerize Python apps using Docker
keywords: Docker, getting started, Python, language
title: What will you learn in this module?
toc_min: 1
toc_max: 2
---
> ### Coming soon
>
> Thanks for your interest in learning how to containerize a Python application. We are actively writing this guide. Watch this space!
Meanwhile, here's an outline of the tasks we are planning to cover. Using the Python getting started guide, you'll learn how to:
* Create a new Dockerfile which contains instructions required to build a Python image
* Build an image and run the newly built image as a container
* Set up volumes and networking
* Orchestrate containers using Compose
* Use containers for development
* Configure a CI/CD pipeline for your application using GitHub Actions
<br />

View File

@ -0,0 +1,11 @@
---
title: "Run your image as a container"
keywords: Python, run, image, container,
description: Learn how to run the image as a container.
---
> ### Coming soon
>
> Thanks for your interest in learning how to containerize a Python application. We are actively working on this topic. Watch this space!
<br />