Developing Nodejs apps with Docker

Source: Internet
Author: User

English version of the original address

This is the first of two serial articles that explains some of the details of using the Docker alternative Vagrant to develop a Express framework-based Nodejs app. However, this time it will be more difficult: we will use Connect-redis to implement the session function in Redis. The second article will continue based on this.

The Node App

This App consists of package.json one server.js , .gitignore and a file, just so simple:

.gitignore:

1  Node_modules/*

package.json:

1 {2"Name": "Docker-dev", 3"Version": "0.1.0", 4"description": "Docker Dev", 5"Dependencies": { 6"Connect-redis": "~1.4.5", 7"Express": "~3.3.3", 8"Hiredis": "~0.1.15", 9"Redis": "~0.8.4"Ten      }  One}

server.js:

1 varExpress = require (' Express '),2App =Express (),3Redis = require (' Redis '),4Redisstore = require (' Connect-redis ')) (Express),5Server = require (' http '). Createserver (app);6 7App.configure (function() {8App.use (Express.cookieparser (' Keyboard-cat ')));9 App.use (express.session ({TenStoreNewRedisstore ({ OneHost:process.env.REDIS_HOST | | ' localhost ', APort:process.env.REDIS_PORT | | 6379, -Db:process.env.REDIS_DB | | 0 -         }), the Cookie: { -Expiresfalse, -MAXAGE:30 * 24 * 60 * 60 * 1000 -         } +     })); - }); +  AApp.get ('/',function(req, res) { at Res.json ({ -Status: "OK" -   }); - }); -  - varPort = Process.env.HTTP_PORT | | 3000; in Server.listen (port); -Console.log (' Listening on port ' + port);

Server.jsThe dependency Express App is processed and one Express App is started, which Session configures Redis the stored information and exposes an endpoint (endpoint) jsonthe server state information used to return the standard format.

It is important to note that Redis's connection information is covered by the environment variables used--which is useful when it is published later.

The Dockerfile

In order to facilitate development, we will put redis and node run in the same container, in order to achieve this, it must be used Dockerfile to configure the container:

Dockerfile:

1From Dockerfile/ubuntu2 3Maintainer Abhinav Ajgaonkar <[email protected]>4 5 # Install Redis6 RUN7apt-get-y-qq Install Python redis-Server8 9 # Install NodeTen RUN OneCd/opt && Awget http://nodejs.org/dist/v0.10.28/node-v0.10.28-linux-x64.tar.gz && \ -TAR-XZF node-v0.10.28-linux-x64.tar.gz &&  -MV node-v0.10.28-linux-x64 Node &&  theCd/usr/local/bin && -Ln-s/opt/node/bin/*. &&  -Rm-f/opt/node-v0.10.28-linux-x64.tar.gz -  + # Set The working directory -Workdir/src +  ACMD ["/bin/bash"]

Let Docherfile 's take a line-by-line look at the code:

1 from Dockerfile/ubuntu

Tells Docker the Docker image file provided dockerfile/ubuntu by the company as the build base image.

1 RUN   2   apt-get-y-qq Install Python redis-server

The underlying image itself does not have anything, so we need apt-get to pack the required components in order. This indicates the installation python and redis-server The Redis service is required because we want to store the session information in. For npm the purposes of, the python Redis Node build extension can be C .

1 RUN   2   3   wget http://nodejs.org/dist/v0.10.28/node-v0.10.28-linux-x64.tar.gz && \4   tar-xzf node-v0.10.28-linux-x64.tar.gz &&5   MV node-v0.10.28-linux-x64 Node &&6   7   ln-s/opt/node/bin/*. &&8    rm-f/opt/node-v0.10.28-linux-x64.tar.gz

Download and unzip the 64 bit binary plate NodeJs .

1 workdir  /src

The phrase is tell Docker --the container starts running when it cd /src enters the directory.

1 CMD ["/bin/bash"]

This is the last step: Start /bin/bash.

Build and run the container

Once the Docker file is configured, let's generate a docker image:

1 Docker build-t sqldump/docker-dev:0.1.

Once the build is successful, you can start the container with the following command:

1 Docker run-i-T--2-            p 3000:30003            4            sqldump/docker-dev:0.1

Let's analyze This command.

-i: Runs the container in interactive mode (unlike -d : Running a container in detach mode), which means that the session container stops running at the end of the interaction.

-t: a virtual terminal ( pseudo-tty )is assigned.

--rm: Removes the container and file system when it stops running.

-p 3000:3000: Host port 3000 : Container port3000

1 -V ' pwd ':/src

This command loads the current working directory of the host (for example, the project file) into the container /src . We load files instead add of using commands to add files, which allows us to see the effect in the container immediately after we love the file in a text editor.

sqldump/docker-dev:0.1: The name and version number of the currently running Docker image is the same as the image we generated.

As Dockerfiles specified CMD ["/bin/bash"] , we entered the container after it was run bash shell . If you docker run the command successfully, the scenario should look like this:

Start Developing

The container is now running, but before you start writing code, you need to install some of the standard, non- docker file files separately. first , start the service in the container with the following command redis :

1 Service redis-server start

then , install the dependent dependencies and nodemon . Nodemonyou can listen to changes in the project file and restart the service in real time.

1 NPM Install 2 npm install-g Nodemon

finally , start the service with the following command:

1 Nodemon server.js

Now, open your browser and visit: http://localhost:3000 , smooth words will appear:

To server.js add an endpoint to simulate the development workflow:

1 function (req, res) {2  Res.json ({3    hello:req.params.name4   }); 5 });

You will be able to see nodemon the file changes detected and restart the service:

Now visit: http://localhost:3000/hello/world and you will see the page:

Production

The current state of the container is far from being molded. redisthe data inside will be lost after the container restarts. Similarly, if you delete this container and regenerate one, the previous data will not be saved. This result is not optimistic, then, in the next chapter, I will explain the product setup and solve the problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.