Home > Software design >  Encrypt DB password in NodeJS application before building and pushing docker image
Encrypt DB password in NodeJS application before building and pushing docker image

Time:03-27

Infrastructure setup:

  • Docker Desktop environment running on MacOS,
  • A Minikube cluster is also running on this MacOS.
  • Jenkins pod running on the Minikube cluster

I have this NodeJS application that talks to a MySQL database(A docker container) to retrieve a text string from a database called hello_world. I need to encrypt the database password before building the application within a NodeJS image. This image will then be pushed to the DockerHub repository.

It will then be downloaded and installed as a pod in the Minikube cluster via a Jenkins Pipeline in the dev namespace. There is a MySQL database pod already setup in the ‘dev’ namespace in which subsequent stages in the pipeline will test the retrieval of the text string from the database.

➜  nodejs-app git:(main) ✗ cat app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');

// parse application/json
app.use(bodyParser.json());

//create database connection
const conn = mysql.createConnection({
  host: 'dev-mysqldb',
  user: 'mysqluser',
  password: ‘xxxxxxxx’,
  database: 'hello_world'
});

//connect to database
conn.connect((err) =>{
  if(err) throw err;
  console.log('Mysql Connected...');
});

//show all products
app.get('/',(req, res) => {
  let sql = "SELECT * FROM messages";
  let query = conn.query(sql, (err, results) => {
    if(err) throw err;
//    res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
    res.send(results);
  });
});

//Server listening
app.listen(80,() =>{
  console.log('Server started on port 80...');
});

I have 2 questions here.

  1. How do I encrypt the database password in the above NodeJS application?
  2. How do I make Kubernete pod decrypt the database password which was originally setup in the docker environment?

Thanks.

CodePudding user response:

The simplest approach here is to use dotenv.

Usage:
Create a .env file in the root of your project:

S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"

As early as possible in your application, import and configure dotenv:

require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it working

.. or using ES6?

import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'

make sure to take a look at https://github.com/motdotla/dotenv#readme for more information.

  • Related