How To Set Up a Node.js Application for Production on Debian 10


Node.js is an open-source JavaScript runtime environment for building server-side and networking applications. The platform runs on Linux, macOS, FreeBSD, and Windows. Though you can run Node.js applications at the command line, this tutorial will focus on running them as a service. This means that the applications will restart on reboot or failure and are safe for use in a production environment.

In this tutorial, you will set up a production-ready Node.js environment on a single Debian 10 server. This server will run a Node.js application managed by PM2, and provide users with secure access to the application through an Nginx reverse proxy. The Nginx server will offer HTTPS, using a free certificate provided by Let’s Encrypt.


This guide assumes that you have the following:

When you’ve completed the prerequisites, you will have a server serving your domain’s default placeholder page at https://your_domain/.

Step 1 — Installing Node.js

Let’s begin by installing the latest LTS release of Node.js, using the NodeSource package archives.

To install the NodeSource PPA and access its contents, you will first need to update your package index and install curl:

  • sudo apt update
  • sudo apt install curl

Make sure you’re in your home directory, and then use curl to retrieve the installation script for the Node.js 10.x archives:

  • cd ~
  • curl -sL -o

You can inspect the contents of this script with nano or your preferred text editor:

  • nano

When you’re done inspecting the script, run it under sudo:

  • sudo bash

The PPA will be added to your configuration and your local package cache will be updated automatically. After running the setup script from Nodesource, you can install the Node.js package:

  • sudo apt install nodejs

To check which version of Node.js you have installed after these initial steps, type:

  • nodejs -v

Note: When installing from the NodeSource PPA, the Node.js executable is called nodejs, rather than node.

The nodejs package contains the nodejs binary as well as npm, a package manager for Node modules, so you don’t need to install npm separately.

npm uses a configuration file in your home directory to keep track of updates. It will be created the first time you run npm. Execute this command to verify that npm is installed and to create the configuration file:

  • npm -v

In order for some npm packages to work (those that require compiling code from source, for example), you will need to install the build-essential package:

  • sudo apt install build-essential

You now have the necessary tools to work with npm packages that require compiling code from source.

With the Node.js runtime installed, we can move on to writing a Node.js application.

Step 2 — Creating a Node.js Application

Let’s write a Hello World application that returns “Hello World” to any HTTP requests. This sample application will help you get Node.js set up. You can replace it with your own application — just make sure that you modify your application to listen on the appropriate IP addresses and ports.

First, let’s create a sample application called hello.js:

  • cd ~
  • nano hello.js

Insert the following code into the file:

const http = require('http');  const hostname = 'localhost'; const port = 3000;  const server = http.createServer((req, res) => {   res.statusCode = 200;   res.setHeader('Content-Type', 'text/plain');   res.end('Hello World!\n'); });  server.listen(port, hostname, () => {   console.log(`Server running at http://$  {hostname}:$  {port}/`); }); 

Save the file and exit the editor.

This Node.js application listens on the specified address (localhost) and port (3000), and returns “Hello World!” with a 200 HTTP success code. Since we’re listening on localhost, remote clients won’t be able to connect to our application.

To test your application, type:

  • node hello.js

You will see the following output:

Server running at http://localhost:3000/

Note: Running a Node.js application in this manner will block additional commands until you kill the application by pressing CTRL+C.

To test the application, open another terminal session on your server, and connect to localhost with curl:

  • curl http://localhost:3000

If you see the following output, the application is working properly and listening on the correct address and port:

Hello World!

If you do not see the expected output, make sure that your Node.js application is running and configured to listen on the proper address and port.

Once you’re sure it’s working, kill the application (if you haven’t already) by pressing CTRL+C.

Step 3 — Installing PM2

Next let’s install PM2, a process manager for Node.js applications. PM2 makes it possible to daemonize applications so that they will run in the background as a service.

Use npm to install the latest version of PM2 on your server:

  • sudo npm install pm2 -g

The -g option tells npm to install the module globally, so it’s available system-wide.

Let’s first use the pm2 start command to run the hello.js application in the background:

  • pm2 start hello.js

This also adds your application to PM2’s process list, which is outputted every time you start an application:

[PM2] Spawning PM2 daemon with pm2_home=/home/sammy/.pm2 [PM2] PM2 Successfully daemonized [PM2] Starting /home/sammy/hello.js in fork_mode (1 instance) [PM2] Done. ┌──────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬───────────┬───────┬──────────┐ │ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │ ├──────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼───────────┼───────┼──────────┤ │ hello │ 0 │ fork │ 1338 │ online │ 0 │ 0s │ 0% │ 23.0 MB │ sammy │ disabled │ └──────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴───────────┴───────┴──────────┘ Use `pm2 show <id|name>` to get more details about an app

As you can see, PM2 automatically assigns an App name based on the filename without the .js extension, along with a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

Applications that are running under PM2 will be restarted automatically if the application crashes or is killed, but we can take an additional step to get the application to launch on system startup using the startup subcommand. This subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots. Type the following:

  • sudo pm2 startup

You will see output that looks like this, describing the service configuration that PM2 has generated:

[PM2] Init System found: systemd Platform systemd Template [Unit] Description=PM2 process manager Documentation= [Service] Type=forking User=root LimitNOFILE=infinity LimitNPROC=infinity LimitCORE=infinity Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin Environment=PM2_HOME=/root/.pm2 PIDFile=/root/.pm2/ Restart=on-failure ExecStart=/usr/lib/node_modules/pm2/bin/pm2 resurrect ExecReload=/usr/lib/node_modules/pm2/bin/pm2 reload all ExecStop=/usr/lib/node_modules/pm2/bin/pm2 kill [Install] Target path /etc/systemd/system/pm2-root.service Command list [ 'systemctl enable pm2-root' ] [PM2] Writing init configuration in /etc/systemd/system/pm2-root.service [PM2] Making script booting at startup... [PM2] [-] Executing: systemctl enable pm2-root... Created symlink /etc/systemd/system/ → /etc/systemd/system/pm2-root.service. [PM2] [v] Command successfully executed. +---------------------------------------+ [PM2] Freeze a process list on reboot via: $ pm2 save [PM2] Remove init script via: $ pm2 unstartup systemd

You have now created a systemd unit that runs pm2 on boot. This pm2 instance, in turn, runs hello.js.

Start the service with systemctl:

  • sudo systemctl start pm2-root.service

Check the status of the systemd unit:

  • systemctl status pm2-root.service

You should see output like the following:

● pm2-root.service - PM2 process manager Loaded: loaded (/etc/systemd/system/pm2-root.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2019-07-12 16:09:54 UTC; 4s ago

For a detailed overview of systemd, see Systemd Essentials: Working with Services, Units, and the Journal.

In addition to those we have covered, PM2 provides many subcommands that allow you to manage or look up information about your applications.

Stop an application with this command (specify the PM2 App name or id):

  • pm2 stop app_name_or_id

Restart an application:

  • pm2 restart app_name_or_id

List the applications currently managed by PM2:

  • pm2 list

Get information about a specific application using its App name:

  • pm2 info app_name

The PM2 process monitor can be pulled up with the monit subcommand. This displays the application status, CPU, and memory usage:

  • pm2 monit

Note that running pm2 without any arguments will also display a help page with example usage.

Now that your Node.js application is running and managed by PM2, let’s set up the reverse proxy.

Step 4 — Setting Up Nginx as a Reverse Proxy Server

Your application is running and listening on localhost, but you need to set up a way for your users to access it. We will set up the Nginx web server as a reverse proxy for this purpose.

In the prerequisite tutorial, you set up your Nginx configuration in the /etc/nginx/sites-available/your_domain file. Open this file for editing:

  • sudo nano /etc/nginx/sites-available/your_domain

Within the server block, you should have an existing location / block. Replace the contents of that block with the following configuration. If your application is set to listen on a different port, update the highlighted portion to the correct port number:

server { ...     location / {         proxy_pass http://localhost:3000;         proxy_http_version 1.1;         proxy_set_header Upgrade $  http_upgrade;         proxy_set_header Connection 'upgrade';         proxy_set_header Host $  host;         proxy_cache_bypass $  http_upgrade;     } ... } 

This configures the server to respond to requests at its root. Assuming our server is available at your_domain, accessing https://your_domain/ via a web browser would send the request to hello.js, listening on port 3000 at localhost.

You can add additional location blocks to the same server block to provide access to other applications on the same server. For example, if you were also running another Node.js application on port 3001, you could add this location block to allow access to it via https://your_domain/app2:

/etc/nginx/sites-available/your_domain — Optional
server { ...     location /app2 {         proxy_pass http://localhost:3001;         proxy_http_version 1.1;         proxy_set_header Upgrade $  http_upgrade;         proxy_set_header Connection 'upgrade';         proxy_set_header Host $  host;         proxy_cache_bypass $  http_upgrade;     } ... } 

Once you are done adding the location blocks for your applications, save the file and exit your editor.

Make sure you didn’t introduce any syntax errors by typing:

  • sudo nginx -t

Restart Nginx:

  • sudo systemctl restart nginx

Assuming that your Node.js application is running and your application and Nginx configurations are correct, you should now be able to access your application via the Nginx reverse proxy. Try it out by accessing your domain in the browser: https://your_domain.


Congratulations! You now have your Node.js application running behind an Nginx reverse proxy on a Debian 10 server. This reverse proxy setup is flexible enough to provide your users access to other applications or static web content that you want to share.

DigitalOcean Community Tutorials

How To Use PostgreSQL with Your Ruby on Rails Application on Ubuntu 18.04


When using the Ruby on Rails web framework, your application is set up by default to use SQLite as a database. SQLite is a lightweight, portable, and user-friendly relational database that performs especially well in low-memory environments, and will work well in many cases. However, for highly complex applications that need more reliable data integrity and programmatic extensibility, a PostgreSQL database will be a more robust and flexible choice. In order to configure your Ruby on Rails setup to use PostgreSQL, you will need to perform a few additional steps to get it up and running.

In this tutorial, you will set up a Ruby on Rails development environment connected to a PostgreSQL database on an Ubuntu 18.04 server. You will install and configure PostgreSQL, and then test your setup by creating a Rails application that uses PostgreSQL as its database server.


This tutorial requires the following:

Step 1 – Installing PostgreSQL

In order to configure Ruby on Rails to create your web application with PostgreSQL as a database, you will first install the database onto your server.

Using sudo privileges, update your APT package index to make sure that your repositories are up to date:

  • sudo apt update

Next, install PostgreSQL and its development libraries:

  • sudo apt install postgresql postgresql-contrib libpq-dev

In the previous command, the postgresql package holds the main PostgreSQL program, while postgresql-contrib adds several PostgreSQL features that extend its capabilities. libpq-dev is a PostgreSQL library that allows clients to send queries and receive responses from the back-end server, which will allow your application to communicate with its database.

Once PostgreSQL and its dependencies are installed, the next step is to create a role that your Rails application will use later to create your database.

Step 2 – Creating a New Database Role

In PostgreSQL, roles can be used in the same way as users in Linux to organize permissions and authorization. This step will show you how to create a new super user role for your Linux username that will allow you to operate within the PostgreSQL system to create and configure databases.

To create a PostgreSQL super user role, use the following command, substituting the highlighted word with your Ubuntu 18.04 username:

  • sudo -u postgres createuser -s sammy -P

Since you specified the -P flag, you will be prompted to enter a password for your new role. Enter your desired password, making sure to record it so that you can use it in a configuration file in a future step.

In this command, you used createuser to create a role named sammy. The -s gave this user super user privileges, and sudo -u allowed you to run the command from the postgres account that is automatically created upon installing PostgreSQL.

Note: Since the authentication mode for PostgreSQL on Ubuntu 18.04 starts out as ident, by default an Ubuntu user can only operate in PostgreSQL with a role of the same name. For more information, check out the PostgreSQL official documentation on authentication.

If you did not use the -P flag and want to set a password for the role after you create it, enter the PostgreSQL console with the following command:

  • sudo -u postgres psql

You will receive the following output, along with the prompt for the PostgreSQL console:

psql (10.9 (Ubuntu 10.9-0ubuntu0.18.04.1)) Type "help" for help. postgres=#

The PostgreSQL console is indicated by the postgres=# prompt. At the PostgreSQL prompt, enter this command to set the password for the new database role, replacing the highlighted name with the one you created:

  • \password sammy

PostgreSQL will prompt you for a password. Enter your desired password at the prompt, then confirm it.

Now, exit the PostgreSQL console by entering this command:

  • \q

Your usual prompt will now reappear.

In this step, you created a new PostgreSQL role with super user privileges. Now you are ready to create a new Rails app that uses this role to create a database.

Step 3 – Creating a New Rails Application

With a role configured for PostgreSQL, you can now create a new Rails application that is set up to use PostgreSQL as a database.

First, navigate to your home directory:

  • cd ~

Create a new Rails application in this directory, replacing appname with whatever you would like to call your app:

  • rails new appname -d=postgresql

The -d=postgresql option sets PostgreSQL as the database.

Once you’ve run this command, a new folder named appname will appear in your home directory, containing all the elements of a basic Rails application.

Next, move into the application’s directory:

  • cd appname

Now that you have created a new Rails application and have moved into the root directory for your project, you can configure and create your PostgreSQL database from within your Rails app.

Step 4 – Configuring and Creating Your Database

When creating the development and test databases for your application, Rails will use the PostgreSQL role that you created for your Ubuntu username. To make sure that Rails creates these databases, you will alter the database configuration file of your project. You will then create your databases.

One of the configuration changes to make in your Rails application is to add the password for the PostgreSQL role you created in the last step. To keep sensitive information like passwords safe, it is a good idea to store this in an environment variable rather than to write it directly in your configuration file.

To store your password in an environment variable at login, run the following command, replacing APPNAME with the name of your app and PostgreSQL_Role_Password with the password you created in the last step:

  • echo 'export APPNAME_DATABASE_PASSWORD="PostgreSQL_Role_Password"' >> ~/.bashrc

This command writes the export command to your ~/.bashrc file so that the environment variable will be set at login.

To export the variable for your current session, use the source command:

  • source ~/.bashrc

Now that you have stored your password in your environment, it’s time to alter the configuration file.

Open your application’s database configuration file in your preferred text editor. This tutorial will use nano:

  • nano config/database.yml

Under the default section, find the line that says pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> and add the following highlighted lines, filling in your credentials and the environment variable you created. It should look something like this:

... default: &default   adapter: postgresql   encoding: unicode   # For details on connection pooling, see Rails configuration guide   #   pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>   username: sammy   password: <%= ENV['APPNAME_DATABASE_PASSWORD'] %>  development:   <<: *default   database: appname_development ... 

This will make the Rails application run the database with the correct role and password. Save and exit by pressing CTRL + x, Y, then ENTER.

For more information on configuring databases in Rails, see the Rails documentation.

Now that you have made changes to config/database.yml, create your application’s databases by using the rails command:

  • rails db:create

Once Rails creates the database, you will receive the following output:

Created database 'appname_development' Created database 'appname_test'

As the output suggests, this command created a development and test database in your PostgreSQL server.

You now have a PostgreSQL database connected to your Rails app. To ensure that your application is working, the next step is to test your configuration.

Step 5 – Testing Your Configuration

To test that your application is able to use the PostgreSQL database, try to run your web application so that it will show up in a browser.

Using the rails server command, run your web application on the built-in webserver in your Rails app, Puma:

  • rails server --binding=

--binding binds your application to a specified IP. By default, this flag will bind Rails to, but since this means that Rails will listen to all interfaces, it is more secure to use to specify the localhost. By default, the application listens on port 3000.

Once your Rails app is running, your command prompt will disappear, replaced by this output:

=> Booting Puma => Rails 5.2.3 application starting in development => Run `rails server -h` for more startup options Puma starting in single mode... * Version 3.12.1 (ruby 2.6.3-p62), codename: Llamas in Pajamas * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp:// Use Ctrl-C to stop

To test if your application is running, open up a new terminal window on your server and use the curl command to send a request to

  • curl

You will receive a lot of output in HTML, ending in something like:

... <strong>Rails version:</strong> 5.2.3<br /> <strong>Ruby version:</strong> 2.6.3 (x86_64-linux) </p> </section> </div> </body> </html>

If your Rails application is on a remote server and you want to access it through a web browser, an easy way is to bind it to the public IP address of your server. First, open port 3000 in your firewall:

  • sudo ufw allow 3000

Next, look up the public IP address of your server. You can do this by running the following curl command:

  • curl

This will return your public IP address. Use it with the rails server command, substituting server_public_IP with your server’s public IP:

  • rails server --binding=server_public_IP

Now you will be able to access your Rails application in a local web browser via the server’s public IP address on port 3000 by visiting:


At this URL, you will find a Ruby on Rails welcome page:

Ruby on Rails Welcome Page

This means that your application is properly configured and connected to the PostgreSQL database.

After testing the configuration, if you would like to close port 3000, use the following command.

  • sudo ufw delete allow 3000


In this tutorial, you created a Ruby on Rails web application that was configured to use PostgreSQL as a database on an Ubuntu 18.04 server. If you would like to learn more about the Ruby programming language, check out our How To Code in Ruby series.

For more information on choosing a database for your application, check out our tutorial on the differences between and use cases of SQLite, PostgreSQL, and MySQL. If you want to read more about how to use databases, see our An Introduction to Queries in PostgreSQL article, or explore DigitalOcean’s Managed Databases product.

DigitalOcean Community Tutorials

Zato Blog: Zato 3.1 Released – Open-Source Python-based API Integrations and Backend Application Server

The newest version of Zato, the open-source Python-based enterprise API integrations platform and backend application server, is out with a lot of interesting features, changes and additions.

The full changelog is here and below is a summary of what is new in 3.1:

  • Greatly enhanced support for Docker, including Quickstart, Swarm and Kubernetes
  • Python 3 is now fully supported in addition to Python 2.7
  • New connectors and adapters: MongoDB, LDAP (Active Directory), Apache Kafka, SFTP, Slack, Telegram and JSON-RPC
  • Extensions to Single Sign-On: two-factor authentication and multi-credentials accounts
  • Rate-limiting and IP white-listing, including hierarchical definitions
  • Extensions to WebSockets: outgoing connections and broadcasts
  • A range of security enhancements, including TOTP two-factor authentication in web-admin
  • General performance boosts – both run-time and server startup

What is Zato?

Zato is an open-source API integrations platform and backend application server composed of several major blocks of functionality:

  • Online request/response integrations using a wide range of protocols, including SAP, Odoo, IBM MQ, REST, AMQP, Search, Email and many more

  • Publish/subscribe message topics with queues and guaranteed delivery

  • Single Sign-On for REST and Python applications

Its HA architecture is highly-scalable and everything comes with a web-based GUI along with a command-line interface and admin APIs.

If you are looking for a highly productive Python-based open-source platform designed specifically to integrate systems or expose APIs in many protocols or data formats, to be used by other servers, frontends or mobile, Zato is the choice.

Quick links:

Planet Python

How To Scale a Node.js Application with MongoDB on Kubernetes Using Helm


Kubernetes is a system for running modern, containerized applications at scale. With it, developers can deploy and manage applications across clusters of machines. And though it can be used to improve efficiency and reliability in single-instance application setups, Kubernetes is designed to run multiple instances of an application across groups of machines.

When creating multi-service deployments with Kubernetes, many developers opt to use the Helm package manager. Helm streamlines the process of creating multiple Kubernetes resources by offering charts and templates that coordinate how these objects interact. It also offers pre-packaged charts for popular open-source projects.

In this tutorial, you will deploy a Node.js application with a MongoDB database onto a Kubernetes cluster using Helm charts. You will use the official Helm MongoDB replica set chart to create a StatefulSet object consisting of three Pods, a Headless Service, and three PersistentVolumeClaims. You will also create a chart to deploy a multi-replica Node.js application using a custom application image. The setup you will build in this tutorial will mirror the functionality of the code described in Containerizing a Node.js Application with Docker Compose and will be a good starting point to build a resilient Node.js application with a MongoDB data store that can scale with your needs.


To complete this tutorial, you will need:

Step 1 — Cloning and Packaging the Application

To use our application with Kubernetes, we will need to package it so that the kubelet agent can pull the image. Before packaging the application, however, we will need to modify the MongoDB connection URI in the application code to ensure that our application can connect to the members of the replica set that we will create with the Helm mongodb-replicaset chart.

Our first step will be to clone the node-mongo-docker-dev repository from the DigitalOcean Community GitHub account. This repository includes the code from the setup described in Containerizing a Node.js Application for Development With Docker Compose, which uses a demo Node.js application with a MongoDB database to demonstrate how to set up a development environment with Docker Compose. You can find more information about the application itself in the series From Containers to Kubernetes with Node.js.

Clone the repository into a directory called node_project:

  • git clone node_project

Navigate to the node_project directory:

  • cd node_project

The node_project directory contains files and directories for a shark information application that works with user input. It has been modernized to work with containers: sensitive and specific configuration information has been removed from the application code and refactored to be injected at runtime, and the application’s state has been offloaded to a MongoDB database.

For more information about designing modern, containerized applications, please see Architecting Applications for Kubernetes and Modernizing Applications for Kubernetes.

When we deploy the Helm mongodb-replicaset chart, it will create:

  • A StatefulSet object with three Pods — the members of the MongoDB replica set. Each Pod will have an associated PersistentVolumeClaim and will maintain a fixed identity in the event of rescheduling.
  • A MongoDB replica set made up of the Pods in the StatefulSet. The set will include one primary and two secondaries. Data will be replicated from the primary to the secondaries, ensuring that our application data remains highly available.

For our application to interact with the database replicas, the MongoDB connection URI in our code will need to include both the hostnames of the replica set members as well as the name of the replica set itself. We therefore need to include these values in the URI.

The file in our cloned repository that specifies database connection information is called db.js. Open that file now using nano or your favorite editor:

  • nano db.js

Currently, the file includes constants that are referenced in the database connection URI at runtime. The values for these constants are injected using Node’s process.env property, which returns an object with information about your user environment at runtime. Setting values dynamically in our application code allows us to decouple the code from the underlying infrastructure, which is necessary in a dynamic, stateless environment. For more information about refactoring application code in this way, see Step 2 of Containerizing a Node.js Application for Development With Docker Compose and the relevant discussion in The 12-Factor App.

The constants for the connection URI and the URI string itself currently look like this:

... const {   MONGO_USERNAME,   MONGO_PASSWORD,   MONGO_HOSTNAME,   MONGO_PORT,   MONGO_DB } = process.env;  ...  const url = `mongodb://$  {MONGO_USERNAME}:$  {MONGO_PASSWORD}@$  {MONGO_HOSTNAME}:$  {MONGO_PORT}/$  {MONGO_DB}?authSource=admin`; ... 

In keeping with a 12FA approach, we do not want to hard code the hostnames of our replica instances or our replica set name into this URI string. The existing MONGO_HOSTNAME constant can be expanded to include multiple hostnames — the members of our replica set — so we will leave that in place. We will need to add a replica set constant to the options section of the URI string, however.

Add MONGO_REPLICASET to both the URI constant object and the connection string:

... const {   MONGO_USERNAME,   MONGO_PASSWORD,   MONGO_HOSTNAME,   MONGO_PORT,   MONGO_DB,   MONGO_REPLICASET } = process.env;  ... const url = `mongodb://$  {MONGO_USERNAME}:$  {MONGO_PASSWORD}@$  {MONGO_HOSTNAME}:$  {MONGO_PORT}/$  {MONGO_DB}?replicaSet=$  {MONGO_REPLICASET}&authSource=admin`; ... 

Using the replicaSet option in the options section of the URI allows us to pass in the name of the replica set, which, along with the hostnames defined in the MONGO_HOSTNAME constant, will allow us to connect to the set members.

Save and close the file when you are finished editing.

With your database connection information modified to work with replica sets, you can now package your application, build the image with the docker build command, and push it to Docker Hub.

Build the image with docker build and the -t flag, which allows you to tag the image with a memorable name. In this case, tag the image with your Docker Hub username and name it node-replicas or a name of your own choosing:

  • docker build -t your_dockerhub_username/node-replicas .

The . in the command specifies that the build context is the current directory.

It will take a minute or two to build the image. Once it is complete, check your images:

  • docker images

You will see the following output:

REPOSITORY TAG IMAGE ID CREATED SIZE your_dockerhub_username/node-replicas latest 56a69b4bc882 7 seconds ago 90.1MB node 10-alpine aa57b0242b33 6 days ago 71MB

Next, log in to the Docker Hub account you created in the prerequisites:

  • docker login -u your_dockerhub_username

When prompted, enter your Docker Hub account password. Logging in this way will create a ~/.docker/config.json file in your non-root user’s home directory with your Docker Hub credentials.

Push the application image to Docker Hub with the docker push command. Remember to replace your_dockerhub_username with your own Docker Hub username:

  • docker push your_dockerhub_username/node-replicas

You now have an application image that you can pull to run your replicated application with Kubernetes. The next step will be to configure specific parameters to use with the MongoDB Helm chart.

Step 2 — Creating Secrets for the MongoDB Replica Set

The stable/mongodb-replicaset chart provides different options when it comes to using Secrets, and we will create two to use with our chart deployment:

  • A Secret for our replica set keyfile that will function as a shared password between replica set members, allowing them to authenticate other members.
  • A Secret for our MongoDB admin user, who will be created as a root user on the admin database. This role will allow you to create subsequent users with limited permissions when deploying your application to production.

With these Secrets in place, we will be able to set our preferred parameter values in a dedicated values file and create the StatefulSet object and MongoDB replica set with the Helm chart.

First, let’s create the keyfile. We will use the openssl command with the rand option to generate a 756 byte random string for the keyfile:

  • openssl rand -base64 756 > key.txt

The output generated by the command will be base64 encoded, ensuring uniform data transmission, and redirected to a file called key.txt, following the guidelines stated in the mongodb-replicaset chart authentication documentation. The key itself must be between 6 and 1024 characters long, consisting only of characters in the base64 set.

You can now create a Secret called keyfilesecret using this file with kubectl create:

  • kubectl create secret generic keyfilesecret --from-file=key.txt

This will create a Secret object in the default namespace, since we have not created a specific namespace for our setup.

You will see the following output indicating that your Secret has been created:

secret/keyfilesecret created

Remove key.txt:

  • rm key.txt

Alternatively, if you would like to save the file, be sure restrict its permissions and add it to your .gitignore file to keep it out of version control.

Next, create the Secret for your MongoDB admin user. The first step will be to convert your desired username and password to base64.

Convert your database username:

  • echo -n 'your_database_username' | base64

Note down the value you see in the output.

Next, convert your password:

  • echo -n 'your_database_password' | base64

Take note of the value in the output here as well.

Open a file for the Secret:

  • nano secret.yaml

Note: Kubernetes objects are typically defined using YAML, which strictly forbids tabs and requires two spaces for indentation. If you would like to check the formatting of any of your YAML files, you can use a linter or test the validity of your syntax using kubectl create with the --dry-run and --validate flags:

  • kubectl create -f your_yaml_file.yaml --dry-run --validate=true

In general, it is a good idea to validate your syntax before creating resources with kubectl.

Add the following code to the file to create a Secret that will define a user and password with the encoded values you just created. Be sure to replace the dummy values here with your own encoded username and password:

apiVersion: v1 kind: Secret metadata:   name: mongo-secret data:   user: your_encoded_username   password: your_encoded_password 

Here, we’re using the key names that the mongodb-replicaset chart expects: user and password. We have named the Secret object mongo-secret, but you are free to name it anything you would like.

Save and close the file when you are finished editing.

Create the Secret object with the following command:

  • kubectl create -f secret.yaml

You will see the following output:

secret/mongo-secret created

Again, you can either remove secret.yaml or restrict its permissions and add it to your .gitignore file.

With your Secret objects created, you can move on to specifying the parameter values you will use with the mongodb-replicaset chart and creating the MongoDB deployment.

Step 3 — Configuring the MongoDB Helm Chart and Creating a Deployment

Helm comes with an actively maintained repository called stable that contains the chart we will be using: mongodb-replicaset. To use this chart with the Secrets we’ve just created, we will create a file with configuration parameter values called mongodb-values.yaml and then install the chart using this file.

Our mongodb-values.yaml file will largely mirror the default values.yaml file in the mongodb-replicaset chart repository. We will, however, make the following changes to our file:

  • We will set the auth parameter to true to ensure that our database instances start with authorization enabled. This means that all clients will be required to authenticate for access to database resources and operations.
  • We will add information about the Secrets we created in the previous Step so that the chart can use these values to create the replica set keyfile and admin user.
  • We will decrease the size of the PersistentVolumes associated with each Pod in the StatefulSet to use the minimum viable DigitalOcean Block Storage unit, 1GB, though you are free to modify this to meet your storage requirements.

Before writing the mongodb-values.yaml file, however, you should first check that you have a StorageClass created and configured to provision storage resources. Each of the Pods in your database StatefulSet will have a sticky identity and an associated PersistentVolumeClaim, which will dynamically provision a PersistentVolume for the Pod. If a Pod is rescheduled, the PersistentVolume will be mounted to whichever node the Pod is scheduled on (though each Volume must be manually deleted if its associated Pod or StatefulSet is permanently deleted).

Because we are working with DigitalOcean Kubernetes, our default StorageClass provisioner is set to dobs.csi.digitalocean.comDigitalOcean Block Storage — which we can check by typing:

  • kubectl get storageclass

If you are working with a DigitalOcean cluster, you will see the following output:

NAME PROVISIONER AGE do-block-storage (default) 21m

If you are not working with a DigitalOcean cluster, you will need to create a StorageClass and configure a provisioner of your choice. For details about how to do this, please see the official documentation.

Now that you have ensured that you have a StorageClass configured, open mongodb-values.yaml for editing:

  • nano mongodb-values.yaml

You will set values in this file that will do the following:

  • Enable authorization.
  • Reference your keyfilesecret and mongo-secret objects.
  • Specify 1Gi for your PersistentVolumes.
  • Set your replica set name to db.
  • Specify 3 replicas for the set.
  • Pin the mongo image to the latest version at the time of writing: 4.1.9.

Paste the following code into the file:

replicas: 3 port: 27017 replicaSetName: db podDisruptionBudget: {} auth:   enabled: true   existingKeySecret: keyfilesecret   existingAdminSecret: mongo-secret imagePullSecrets: [] installImage:   repository: unguiculus/mongodb-install   tag: 0.7   pullPolicy: Always copyConfigImage:   repository: busybox   tag: 1.29.3   pullPolicy: Always image:   repository: mongo   tag: 4.1.9   pullPolicy: Always extraVars: {} metrics:   enabled: false   image:     repository: ssalaues/mongodb-exporter     tag: 0.6.1     pullPolicy: IfNotPresent   port: 9216   path: /metrics   socketTimeout: 3s   syncTimeout: 1m   prometheusServiceDiscovery: true   resources: {} podAnnotations: {} securityContext:   enabled: true   runAsUser: 999   fsGroup: 999   runAsNonRoot: true init:   resources: {}   timeout: 900 resources: {} nodeSelector: {} affinity: {} tolerations: [] extraLabels: {} persistentVolume:   enabled: true   #storageClass: "-"   accessModes:     - ReadWriteOnce   size: 1Gi   annotations: {} serviceAnnotations: {} terminationGracePeriodSeconds: 30 tls:   enabled: false configmap: {} readinessProbe:   initialDelaySeconds: 5   timeoutSeconds: 1   failureThreshold: 3   periodSeconds: 10   successThreshold: 1 livenessProbe:   initialDelaySeconds: 30   timeoutSeconds: 5   failureThreshold: 3   periodSeconds: 10   successThreshold: 1 

The persistentVolume.storageClass parameter is commented out here: removing the comment and setting its value to "-" would disable dynamic provisioning. In our case, because we are leaving this value undefined, the chart will choose the default provisioner — in our case,

Also note the accessMode associated with the persistentVolume key: ReadWriteOnce means that the provisioned volume will be read-write only by a single node. Please see the documentation for more information about different access modes.

To learn more about the other parameters included in the file, see the configuration table included with the repo.

Save and close the file when you are finished editing.

Before deploying the mongodb-replicaset chart, you will want to update the stable repo with the helm repo update command:

  • helm repo update

This will get the latest chart information from the stable repository.

Finally, install the chart with the following command:

  • helm install --name mongo -f mongodb-values.yaml stable/mongodb-replicaset

Note: Before installing a chart, you can run helm install with the --dry-run and --debug options to check the generated manifests for your release:

  • helm install --name your_release_name -f your_values_file.yaml --dry-run --debug your_chart

Note that we are naming the Helm release mongo. This name will refer to this particular deployment of the chart with the configuration options we’ve specified. We’ve pointed to these options by including the -f flag and our mongodb-values.yaml file.

Also note that because we did not include the --namespace flag with helm install, our chart objects will be created in the default namespace.

Once you have created the release, you will see output about its status, along with information about the created objects and instructions for interacting with them:

NAME: mongo LAST DEPLOYED: Tue Apr 16 21:51:05 2019 NAMESPACE: default STATUS: DEPLOYED RESOURCES: ==> v1/ConfigMap NAME DATA AGE mongo-mongodb-replicaset-init 1 1s mongo-mongodb-replicaset-mongodb 1 1s mongo-mongodb-replicaset-tests 1 0s ...

You can now check on the creation of your Pods with the following command:

  • kubectl get pods

You will see output like the following as the Pods are being created:

NAME READY STATUS RESTARTS AGE mongo-mongodb-replicaset-0 1/1 Running 0 67s mongo-mongodb-replicaset-1 0/1 Init:0/3 0 8s

The READY and STATUS outputs here indicate that the Pods in our StatefulSet are not fully ready: the Init Containers associated with the Pod’s containers are still running. Because StatefulSet members are created in sequential order, each Pod in the StatefulSet must be Running and Ready before the next Pod will be created.

Once the Pods have been created and all of their associated containers are running, you will see this output:

NAME READY STATUS RESTARTS AGE mongo-mongodb-replicaset-0 1/1 Running 0 2m33s mongo-mongodb-replicaset-1 1/1 Running 0 94s mongo-mongodb-replicaset-2 1/1 Running 0 36s

The Running STATUS indicates that your Pods are bound to nodes and that the containers associated with those Pods are running. READY indicates how many containers in a Pod are running. For more information, please consult the documentation on Pod lifecycles.

If you see unexpected phases in the STATUS column, remember that you can troubleshoot your Pods with the following commands:

  • kubectl describe pods your_pod
  • kubectl logs your_pod

Each of the Pods in your StatefulSet has a name that combines the name of the StatefulSet with the ordinal index of the Pod. Because we created three replicas, our StatefulSet members are numbered 0-2, and each has a stable DNS entry comprised of the following elements: $ (statefulset-name)-$ (ordinal).$ (service name).$ (namespace).svc.cluster.local.

In our case, the StatefulSet and the Headless Service created by the mongodb-replicaset chart have the same names:

  • kubectl get statefulset
NAME READY AGE mongo-mongodb-replicaset 3/3 4m2s
  • kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP <none> 443/TCP 42m mongo-mongodb-replicaset ClusterIP None <none> 27017/TCP 4m35s mongo-mongodb-replicaset-client ClusterIP None <none> 27017/TCP 4m35s

This means that the first member of our StatefulSet will have the following DNS entry:


Because we need our application to connect to each MongoDB instance, it’s essential that we have this information so that we can communicate directly with the Pods, rather than with the Service. When we create our custom application Helm chart, we will pass the DNS entries for each Pod to our application using environment variables.

With your database instances up and running, you are ready to create the chart for your Node application.

Step 4 — Creating a Custom Application Chart and Configuring Parameters

We will create a custom Helm chart for our Node application and modify the default files in the standard chart directory so that our application can work with the replica set we have just created. We will also create files to define ConfigMap and Secret objects for our application.

First, create a new chart directory called nodeapp with the following command:

  • helm create nodeapp

This will create a directory called nodeapp in your ~/node_project folder with the following resources:

  • A Chart.yaml file with basic information about your chart.
  • A values.yaml file that allows you to set specific parameter values, as you did with your MongoDB deployment.
  • A .helmignore file with file and directory patterns that will be ignored when packaging charts.
  • A templates/ directory with the template files that will generate Kubernetes manifests.
  • A templates/tests/ directory for test files.
  • A charts/ directory for any charts that this chart depends on.

The first file we will modify out of these default files is values.yaml. Open that file now:

  • nano nodeapp/values.yaml

The values that we will set here include:

  • The number of replicas.
  • The application image we want to use. In our case, this will be the node-replicas image we created in Step 1.
  • The ServiceType. In this case, we will specify LoadBalancer to create a point of access to our application for testing purposes. Because we are working with a DigitalOcean Kubernetes cluster, this will create a DigitalOcean Load Balancer when we deploy our chart. In production, you can configure your chart to use Ingress Resources and Ingress Controllers to route traffic to your Services.
  • The targetPort to specify the port on the Pod where our application will be exposed.

We will not enter environment variables into this file. Instead, we will create templates for ConfigMap and Secret objects and add these values to our application Deployment manifest, located at ~/node_project/nodeapp/templates/deployment.yaml.

Configure the following values in the values.yaml file:

# Default values for nodeapp. # This is a YAML-formatted file. # Declare variables to be passed into your templates.  replicaCount: 3  image:   repository: your_dockerhub_username/node-replicas   tag: latest   pullPolicy: IfNotPresent  nameOverride: "" fullnameOverride: ""  service:   type: LoadBalancer   port: 80   targetPort: 8080 ... 

Save and close the file when you are finished editing.

Next, open a secret.yaml file in the nodeapp/templates directory:

  • nano nodeapp/templates/secret.yaml

In this file, add values for your MONGO_USERNAME and MONGO_PASSWORD application constants. These are the constants that your application will expect to have access to at runtime, as specified in db.js, your database connection file. As you add the values for these constants, remember to the use the base64-encoded values that you used earlier in Step 2 when creating your mongo-secret object. If you need to recreate those values, you can return to Step 2 and run the relevant commands again.

Add the following code to the file:

apiVersion: v1 kind: Secret metadata:   name: {{ .Release.Name }}-auth data:   MONGO_USERNAME: your_encoded_username   MONGO_PASSWORD: your_encoded_password 

The name of this Secret object will depend on the name of your Helm release, which you will specify when you deploy the application chart.

Save and close the file when you are finished.

Next, open a file to create a ConfigMap for your application:

  • nano nodeapp/templates/configmap.yaml

In this file, we will define the remaining variables that our application expects: MONGO_HOSTNAME, MONGO_PORT, MONGO_DB, and MONGO_REPLICASET. Our MONGO_HOSTNAME variable will include the DNS entry for each instance in our replica set, since this is what the MongoDB connection URI requires.

According to the Kubernetes documentation, when an application implements liveness and readiness checks, SRV records should be used when connecting to the Pods. As discussed in Step 3, our Pod SRV records follow this pattern: $ (statefulset-name)-$ (ordinal).$ (service name).$ (namespace).svc.cluster.local. Since our MongoDB StatefulSet implements liveness and readiness checks, we should use these stable identifiers when defining the values of the MONGO_HOSTNAME variable.

Add the following code to the file to define the MONGO_HOSTNAME, MONGO_PORT, MONGO_DB, and MONGO_REPLICASET variables. You are free to use another name for your MONGO_DB database, but your MONGO_HOSTNAME and MONGO_REPLICASET values must be written as they appear here:

apiVersion: v1 kind: ConfigMap metadata:   name: {{ .Release.Name }}-config data:   MONGO_HOSTNAME: "mongo-mongodb-replicaset-0.mongo-mongodb-replicaset.default.svc.cluster.local,mongo-mongodb-replicaset-1.mongo-mongodb-replicaset.default.svc.cluster.local,mongo-mongodb-replicaset-2.mongo-mongodb-replicaset.default.svc.cluster.local"     MONGO_PORT: "27017"   MONGO_DB: "sharkinfo"   MONGO_REPLICASET: "db" 

Because we have already created the StatefulSet object and replica set, the hostnames that are listed here must be listed in your file exactly as they appear in this example. If you destroy these objects and rename your MongoDB Helm release, then you will need to revise the values included in this ConfigMap. The same applies for MONGO_REPLICASET, since we specified the replica set name with our MongoDB release.

Also note that the values listed here are quoted, which is the expectation for environment variables in Helm.

Save and close the file when you are finished editing.

With your chart parameter values defined and your Secret and ConfigMap manifests created, you can edit the application Deployment template to use your environment variables.

Step 5 — Integrating Environment Variables into Your Helm Deployment

With the files for our application Secret and ConfigMap in place, we will need to make sure that our application Deployment can use these values. We will also customize the liveness and readiness probes that are already defined in the Deployment manifest.

Open the application Deployment template for editing:

  • nano nodeapp/templates/deployment.yaml

Though this is a YAML file, Helm templates use a different syntax from standard Kubernetes YAML files in order to generate manifests. For more information about templates, see the Helm documentation.

In the file, first add an env key to your application container specifications, below the imagePullPolicy key and above ports:

apiVersion: apps/v1 kind: Deployment metadata: ...   spec:     containers:       - name: {{ .Chart.Name }}         image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"         imagePullPolicy: {{ .Values.image.pullPolicy }}         env:         ports: 

Next, add the following keys to the list of env variables:

apiVersion: apps/v1 kind: Deployment metadata: ...   spec:     containers:       - name: {{ .Chart.Name }}         image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"         imagePullPolicy: {{ .Values.image.pullPolicy }}         env:         - name: MONGO_USERNAME           valueFrom:             secretKeyRef:               key: MONGO_USERNAME               name: {{ .Release.Name }}-auth         - name: MONGO_PASSWORD           valueFrom:             secretKeyRef:               key: MONGO_PASSWORD               name: {{ .Release.Name }}-auth         - name: MONGO_HOSTNAME           valueFrom:             configMapKeyRef:               key: MONGO_HOSTNAME               name: {{ .Release.Name }}-config         - name: MONGO_PORT           valueFrom:             configMapKeyRef:               key: MONGO_PORT               name: {{ .Release.Name }}-config         - name: MONGO_DB           valueFrom:             configMapKeyRef:               key: MONGO_DB               name: {{ .Release.Name }}-config               - name: MONGO_REPLICASET           valueFrom:             configMapKeyRef:               key: MONGO_REPLICASET               name: {{ .Release.Name }}-config         

Each variable includes a reference to its value, defined either by a secretKeyRef key, in the case of Secret values, or configMapKeyRef for ConfigMap values. These keys point to the Secret and ConfigMap files we created in the previous Step.

Next, under the ports key, modify the containerPort definition to specify the port on the container where our application will be exposed:

apiVersion: apps/v1 kind: Deployment metadata: ...   spec:     containers:     ...       env:     ...       ports:         - name: http           containerPort: 8080           protocol: TCP       ... 

Next, let’s modify the liveness and readiness checks that are included in this Deployment manifest by default. These checks ensure that our application Pods are running and ready to serve traffic:

  • Readiness probes assess whether or not a Pod is ready to serve traffic, stopping all requests to the Pod until the checks succeed.
  • Liveness probes check basic application behavior to determine whether or not the application in the container is running and behaving as expected. If a liveness probe fails, Kubernetes will restart the container.

For more about both, see the relevant discussion in Architecting Applications for Kubernetes.

In our case, we will build on the httpGet request that Helm has provided by default and test whether or not our application is accepting requests on the /sharks endpoint. The kubelet service will perform the probe by sending a GET request to the Node server running in the application Pod’s container and listening on port 8080. If the status code for the response is between 200 and 400, then the kubelet will conclude that the container is healthy. Otherwise, in the case of a 400 or 500 status, kubelet will either stop traffic to the container, in the case of the readiness probe, or restart the container, in the case of the liveness probe.

Add the following modification to the stated path for the liveness and readiness probes:

apiVersion: apps/v1 kind: Deployment metadata: ...   spec:     containers:     ...       env:     ...       ports:         - name: http           containerPort: 8080           protocol: TCP       livenessProbe:         httpGet:           path: /sharks           port: http       readinessProbe:         httpGet:           path: /sharks           port: http 

Save and close the file when you are finished editing.

You are now ready to create your application release with Helm. Run the following helm install command, which includes the name of the release and the location of the chart directory:

  • helm install --name nodejs ./nodeapp

Remember that you can run helm install with the --dry-run and --debug options first, as discussed in Step 3, to check the generated manifests for your release.

Again, because we are not including the --namespace flag with helm install, our chart objects will be created in the default namespace.

You will see the following output indicating that your release has been created:

NAME: nodejs LAST DEPLOYED: Wed Apr 17 18:10:29 2019 NAMESPACE: default STATUS: DEPLOYED RESOURCES: ==> v1/ConfigMap NAME DATA AGE nodejs-config 4 1s ==> v1/Deployment NAME READY UP-TO-DATE AVAILABLE AGE nodejs-nodeapp 0/3 3 0 1s ...

Again, the output will indicate the status of the release, along with information about the created objects and how you can interact with them.

Check the status of your Pods:

  • kubectl get pods
NAME READY STATUS RESTARTS AGE mongo-mongodb-replicaset-0 1/1 Running 0 57m mongo-mongodb-replicaset-1 1/1 Running 0 56m mongo-mongodb-replicaset-2 1/1 Running 0 55m nodejs-nodeapp-577df49dcc-b5fq5 1/1 Running 0 117s nodejs-nodeapp-577df49dcc-bkk66 1/1 Running 0 117s nodejs-nodeapp-577df49dcc-lpmt2 1/1 Running 0 117s

Once your Pods are up and running, check your Services:

  • kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP <none> 443/TCP 96m mongo-mongodb-replicaset ClusterIP None <none> 27017/TCP 58m mongo-mongodb-replicaset-client ClusterIP None <none> 27017/TCP 58m nodejs-nodeapp LoadBalancer your_lb_ip 80:31518/TCP 3m22s

The EXTERNAL_IP associated with the nodejs-nodeapp Service is the IP address where you can access the application from outside of the cluster. If you see a <pending> status in the EXTERNAL_IP column, this means that your load balancer is still being created.

Once you see an IP in that column, navigate to it in your browser: http://your_lb_ip.

You should see the following landing page:

Application Landing Page

Now that your replicated application is working, let’s add some test data to ensure that replication is working between members of the replica set.

Step 6 — Testing MongoDB Replication

With our application running and accessible through an external IP address, we can add some test data and ensure that it is being replicated between the members of our MongoDB replica set.

First, make sure you have navigated your browser to the application landing page:

Application Landing Page

Click on the Get Shark Info button. You will see a page with an entry form where you can enter a shark name and a description of that shark’s general character:

Shark Info Form

In the form, add an initial shark of your choosing. To demonstrate, we will add Megalodon Shark to the Shark Name field, and Ancient to the Shark Character field:

Filled Shark Form

Click on the Submit button. You will see a page with this shark information displayed back to you:

Shark Output

Now head back to the shark information form by clicking on Sharks in the top navigation bar:

Shark Info Form

Enter a new shark of your choosing. We’ll go with Whale Shark and Large:

Enter New Shark

Once you click Submit, you will see that the new shark has been added to the shark collection in your database:

Complete Shark Collection

Let’s check that the data we’ve entered has been replicated between the primary and secondary members of our replica set.

Get a list of your Pods:

  • kubectl get pods
NAME READY STATUS RESTARTS AGE mongo-mongodb-replicaset-0 1/1 Running 0 74m mongo-mongodb-replicaset-1 1/1 Running 0 73m mongo-mongodb-replicaset-2 1/1 Running 0 72m nodejs-nodeapp-577df49dcc-b5fq5 1/1 Running 0 5m4s nodejs-nodeapp-577df49dcc-bkk66 1/1 Running 0 5m4s nodejs-nodeapp-577df49dcc-lpmt2 1/1 Running 0 5m4s

To access the mongo shell on your Pods, you can use the kubectl exec command and the username you used to create your mongo-secret in Step 2. Access the mongo shell on the first Pod in the StatefulSet with the following command:

  • kubectl exec -it mongo-mongodb-replicaset-0 -- mongo -u your_database_username -p --authenticationDatabase admin

When prompted, enter the password associated with this username:

MongoDB shell version v4.1.9 Enter password:

You will be dropped into an administrative shell:

MongoDB server version: 4.1.9 Welcome to the MongoDB shell. ... db:PRIMARY>

Though the prompt itself includes this information, you can manually check to see which replica set member is the primary with the rs.isMaster() method:

  • rs.isMaster()

You will see output like the following, indicating the hostname of the primary:

db:PRIMARY> rs.isMaster() { "hosts" : [ "mongo-mongodb-replicaset-0.mongo-mongodb-replicaset.default.svc.cluster.local:27017", "mongo-mongodb-replicaset-1.mongo-mongodb-replicaset.default.svc.cluster.local:27017", "mongo-mongodb-replicaset-2.mongo-mongodb-replicaset.default.svc.cluster.local:27017" ], ... "primary" : "mongo-mongodb-replicaset-0.mongo-mongodb-replicaset.default.svc.cluster.local:27017", ...

Next, switch to your sharkinfo database:

  • use sharkinfo
switched to db sharkinfo

List the collections in the database:

  • show collections

Output the documents in the collection:

  • db.sharks.find()

You will see the following output:

{ "_id" : ObjectId("5cb7702c9111a5451c6dc8bb"), "name" : "Megalodon Shark", "character" : "Ancient", "__v" : 0 } { "_id" : ObjectId("5cb77054fcdbf563f3b47365"), "name" : "Whale Shark", "character" : "Large", "__v" : 0 }

Exit the MongoDB Shell:

  • exit

Now that we have checked the data on our primary, let’s check that it’s being replicated to a secondary. kubectl exec into mongo-mongodb-replicaset-1 with the following command:

  • kubectl exec -it mongo-mongodb-replicaset-1 -- mongo -u your_database_username -p --authenticationDatabase admin

Once in the administrative shell, we will need to use the db.setSlaveOk() method to permit read operations from the secondary instance:

  • db.setSlaveOk(1)

Switch to the sharkinfo database:

  • use sharkinfo
switched to db sharkinfo

Permit the read operation of the documents in the sharks collection:

  • db.setSlaveOk(1)

Output the documents in the collection:

  • db.sharks.find()

You should now see the same information that you saw when running this method on your primary instance:

db:SECONDARY> db.sharks.find() { "_id" : ObjectId("5cb7702c9111a5451c6dc8bb"), "name" : "Megalodon Shark", "character" : "Ancient", "__v" : 0 } { "_id" : ObjectId("5cb77054fcdbf563f3b47365"), "name" : "Whale Shark", "character" : "Large", "__v" : 0 }

This output confirms that your application data is being replicated between the members of your replica set.


You have now deployed a replicated, highly-available shark information application on a Kubernetes cluster using Helm charts. This demo application and the workflow outlined in this tutorial can act as a starting point as you build custom charts for your application and take advantage of Helm’s stable repository and other chart repositories.

As you move toward production, consider implementing the following:

To learn more about Helm, see An Introduction to Helm, the Package Manager for Kubernetes, How To Install Software on Kubernetes Clusters with the Helm Package Manager, and the Helm documentation.

DigitalOcean Community Tutorials

Podcast.__init__: Web Application Development Entirely In Python

The knowledge and effort required for building a fully functional web application has grown at an accelerated rate over the past several years. This introduces a barrier to entry that excludes large numbers of people who could otherwise be producing valuable and interesting services. To make the onramp easier Meredydd Luff and Ian Davies created Anvil, a platform for full stack web development in pure Python. In this episode Meredydd explains how the Anvil platform is built and how you can use it to build and deploy your own projects. He also shares some examples of people who were able to create profitable businesses themselves because of the reduced complexity. It was interesting to get Meredydd’s perspective on the state of the industry for web development and hear his vision of how Anvil is working to make it available for everyone.


The knowledge and effort required for building a fully functional web application has grown at an accelerated rate over the past several years. This introduces a barrier to entry that excludes large numbers of people who could otherwise be producing valuable and interesting services. To make the onramp easier Meredydd Luff and Ian Davies created Anvil, a platform for full stack web development in pure Python. In this episode Meredydd explains how the Anvil platform is built and how you can use it to build and deploy your own projects. He also shares some examples of people who were able to create profitable businesses themselves because of the reduced complexity. It was interesting to get Meredydd’s perspective on the state of the industry for web development and hear his vision of how Anvil is working to make it available for everyone.


  • Hello and welcome to Podcast.__init__, the podcast about Python and the people who make it great.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With 200 Gbit/s private networking, scalable shared block storage, node balancers, and a 40 Gbit/s public network, all controlled by a brand new API you’ve got everything you need to scale up. And for your tasks that need fast computation, such as training machine learning models, they just launched dedicated CPU instances. Go to to get a $ 20 credit and launch a new server in under a minute. And don’t forget to thank them for their continued support of this show!
  • And to keep track of how your team is progressing on building new features and squashing bugs, you need a project management system designed by software engineers, for software engineers. Clubhouse lets you craft a workflow that fits your style, including per-team tasks, cross-project epics, a large suite of pre-built integrations, and a simple API for crafting your own. With such an intuitive tool it’s easy to make sure that everyone in the business is on the same page. Podcast.init listeners get 2 months free on any plan by going to today and signing up for a trial.
  • Bots and automation are taking over whole categories of online interaction. is an online community designed to serve as a platform-agnostic digital space for bot developers and enthusiasts of all skill levels to learn from one another, share their stories, and move the conversation forward together. They regularly publish guides and resources to help you learn about topics such as bot development, using them for business, and the latest in chatbot news. For newcomers to the space they have the Beginners Guide To Bots that will teach you the basics of how bots work, what they can do, and where they are developed and published. To help you choose the right framework and avoid the confusion about which NLU features and platform APIs you will need they have compiled a list of the major options and how they compare. Go to today to get started and thank them for their support of the show.
  • You listen to this show to learn and stay up to date with the ways that Python is being used, including the latest in machine learning and data analysis. For even more opportunities to meet, listen, and learn from your peers you don’t want to miss out on this year’s conference season. We have partnered with organizations such as O’Reilly Media, Dataversity, and the Open Data Science Conference. Coming up this fall is the combined events of Graphorum and the Data Architecture Summit. The agendas have been announced and super early bird registration for up to $ 300 off is available until July 26th, with early bird pricing for up to $ 200 off through August 30th. Use the code BNLLC to get an additional 10% off any pass when you register. Go to to learn more and take advantage of our partner discounts when you register.
  • The Python Software Foundation is the lifeblood of the community, supporting all of us who want to run workshops and conferences, run development sprints or meetups, and ensuring that PyCon is a success every year. They have extended the deadline for their 2019 fundraiser until June 30th and they need help to make sure they reach their goal. Go to today to make a donation. If you’re listening to this after June 30th of 2019 then consider making a donation anyway!
  • Visit the site to subscribe to the show, sign up for the newsletter, and read the show notes. And if you have any questions, comments, or suggestions I would love to hear them. You can reach me on Twitter at @Podcast__init__ or email
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
  • Join the community in the new Zulip chat workspace at
  • Your host as usual is Tobias Macey and today I’m interviewing Meredydd Luff about Anvil, platform for building full stack web applications entirely in Python


  • Introductions
  • How did you get introduced to Python?
  • Can you start by explaining what Anvil is and the story of how and why you created it?
  • Web applications come in a vast array of styles. What are the primary formats of web applications that Anvil supports building and what are its limitations?
  • Are there certain categories of users that tend to gravitate toward Anvil?
    • How do you approach user experience design and overall usability given the varied backgrounds of your customers?
  • For someone who wants to use Anvil can you talk through a typical workflow and highlight the different components of the platform?
  • Can you describe how Anvil itself is implemented and how it has evolved since you first began working on it?
    • For the javascript transpilation, are you using an existing project such as Transcrypt or PyJS, or did you develop your own?
  • Given that the Python dependencies on your servers are managed by how, how do you approach version upgrades to avoid breaking your customer’s applications?
  • What are the main assumptions that you had going into the project and how have those assumptions been challenged or updated in the process of growing the business?
  • What have been some of the biggest challenges that you have faced in the process of building and growing Anvil?
    • What are some of the edge cases that you have run into while developing Anvil? (e.g. browser APIs, javascript <-> Python impedance mismatch, etc.)
  • Can you talk through how you manage deployments of your customer’s applications?
  • What are some of the features of Anvil that are often overlooked, under-utilized, or misunderstood which you think users would benefit from knowing about?
  • What are some of the most interesting/innovative/unexpected ways that you have seen Anvil used?
  • What are the limitations of Anvil and when is it the wrong choice?
  • What do you have planned for the future of Anvil?

Keep In Touch



The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA

Planet Python