How to Connect NodeJS App in Docker to Oracle Database

How to Connect NodeJS App in Docker to Oracle Database

In this post, I’ll cover how to make a connection from a NodeJS application in a Docker container to your Oracle Database in three different scenarios.

In this post, I’ll cover how to make a connection from a NodeJS application in a Docker container to your Oracle Database in three different scenarios.

  • Typical Database connection.
  • Database inside a different Docker container.
  • Oracle Autonomous Transaction Processing Cloud Database.
Simple Test App

When attempting something new, I find it’s best to make sure all of the pieces that are not part of the new thing, are as simple as possible.

For my examples, I will be using a small NodeJS application that:

  • Connects to the Oracle Database
  • Runs a simple query.
  • Prints the results to the console.

Create a new file named dbConfig.js to set the database connection information.

module.exports = {
  user          : process.env.NODE_ORACLEDB_USER,
  password      : process.env.NODE_ORACLEDB_PASSWORD,
  connectString : process.env.NODE_ORACLEDB_CONNECTIONSTRING,
  poolMax: 2,
  poolMin: 2,
  poolIncrement: 0
};

Create a new file named server.js used to test the connection.

const oracledb = require('oracledb');
const config = require('./dbConfig.js');

async function runTest() {
  let conn;

  try {
    conn = await oracledb.getConnection(config);

    const result = await conn.execute(
      'select current_timestamp from dual'
    );

    console.log(result);
  } catch (err) {
    console.error(err);
  } finally {
    if (conn) {
      try {
        await conn.close();
      } catch (err) {
        console.error(err);
      }
    }
  }
}

runTest();

Install the node-oracledb driver. (If you have any questions about the node-oracledb driver, you can find the answers here.)

npm install oracledb -s

Create environment variables for the connection information. (Replace my values with yours.)

export NODE_ORACLEDB_USER=NotMyRealUser
export NODE_ORACLEDB_PASSWORD=NotMyRealPassword
export NODE_ORACLEDB_CONNECTIONSTRING=192.168.0.44:1521/NotMyRealServiceName

Test the NodeJS application. You should see something similar to the following.

@OraBlaineOS:SimpleApp$ node server.js 
{
  metaData: [ { name: 'CURRENT_TIMESTAMP' } ],
  rows: [ [ 2019-08-20T17:50:38.615Z ] ]
}
Create a Docker Container for the NodeJS App

Create a Dockerfile

FROM oraclelinux:7-slim

# Create app directory
WORKDIR /usr/src/app

# Copy the .js files from your host machine into the new app directory
ADD *.js ./

# Update Oracle Linux
# Install NodeJS
# Install the Oracle Instant Client
# Check that NodeJS and NPM installed correctly
# Install the OracleDB driver
RUN yum update -y && \
  yum install -y oracle-release-el7 && \
  yum install -y oracle-nodejs-release-el7 && \
  yum install -y --disablerepo=ol7_developer_EPEL nodejs && \
  yum install -y oracle-instantclient19.3-basic.x86_64 && \
  yum clean all && \
  node --version && \
  npm --version && \
  npm install oracledb && \
  echo Installed

CMD ["node", "server.js"]

Build the image

docker build --no-cache --force-rm=true -t node_example .

Now that you have an image you’ll run a container and to connect it to:

Typical Oracle Database

docker run \
--name typical_node_example -it \
-e NODE_ORACLEDB_USER=$NODE_ORACLEDB_USER \
-e NODE_ORACLEDB_PASSWORD=$NODE_ORACLEDB_PASSWORD \
-e NODE_ORACLEDB_CONNECTIONSTRING=$NODE_ORACLEDB_CONNECTIONSTRING \
node_example

The container will run, execute the query, and stop. You should see something similar to this output.

{ metaData: [ { name: 'CURRENT_TIMESTAMP' } ],
  rows: [ [ 2019-08-20T18:15:23.615Z ] ] }

An Oracle Database Inside a Docker Container

Created a Docker Network.

docker network create OrdsXeNet

You’ll use that same network to connect from the NodeJS container to the Oracle XE container.

First, change your NODE_ORACLEDB_CONNECTIONSTRING environment variable to use the Oracle XE container name.

export NODE_ORACLEDB_CONNECTIONSTRING=oracleXe:1521/xepdb1

Now, when you run a new docker container, you will attach it to the same Docker Network as the Oracle XE container.

docker run \
--name docker_network_node_example -it \
--network=OrdsXeNet \
-e NODE_ORACLEDB_USER=$NODE_ORACLEDB_USER \
-e NODE_ORACLEDB_PASSWORD=$NODE_ORACLEDB_PASSWORD \
-e NODE_ORACLEDB_CONNECTIONSTRING=$NODE_ORACLEDB_CONNECTIONSTRING \
node_example

The container will run, execute the query, and stop. You should see something similar to this output.

{ metaData: [ { name: 'CURRENT_TIMESTAMP' } ],
  rows: [ [ 2019-08-27T16:42:16.122Z ] ] }

Since both containers are using the same Docker network, you do not need to open the port when you run the Oracle XE container. This is useful if you’d like to keep your database private inside the Docker environment.

Oracle Autonomous Transaction Processing Cloud Database

After you create an Oracle ATP Cloud Database, you’ll need to download the credentials file and extract it into a secure location.

For this database, you will be using an entry in the tnsnames.ora file to make the database connection. Change the NODE_ORACLEDB_CONNECTIONSTRING environment variable to use the tnsnames entry.

export NODE_ORACLEDB_CONNECTIONSTRING=projects_tp

Before you run the container, you need to modify the sqlnet.ora file found in the credentials directory. Change the wallet location to the value that will be mapped inside the Docker container.

WALLET_LOCATION = (SOURCE = (METHOD = file) (METHOD_DATA = (DIRECTORY="/wallet/")))

When you run the new container for the node app, you will map a volume from the directory where you extracted your credentials file to the internal container directory. Mapping a volume makes sure that there is not a copy of the credential files inside the Docker container.

-v /my/host/machine/credentials/directory:/wallet

Finally, when you run the new container, you will add an additional environment variable defining where the tns admin information is located.

-e TNS_ADMIN=/wallet

The full command looks like this:

docker run \
--name cloud_atp_node_example -it \
-v /my/host/machine/credentials/directory:/wallet \
-e NODE_ORACLEDB_USER=$NODE_ORACLEDB_USER \
-e NODE_ORACLEDB_PASSWORD=$NODE_ORACLEDB_PASSWORD \
-e NODE_ORACLEDB_CONNECTIONSTRING=$NODE_ORACLEDB_CONNECTIONSTRING \
-e TNS_ADMIN=/wallet \
-p 3000:3000 \
node_example

The container will run, execute the query, and stop. You should see something similar to this output.

{ metaData: [ { name: 'CURRENT_TIMESTAMP' } ],
  rows: [ [ 2019-08-27T18:21:26.298Z ] ] }

Same Docker Image for all of the Examples

You may have noticed that you only built the Docker image once at the beginning of the post. The application in the Docker image uses environment variables to connect to the database. This allows you to run the same application in one or more containers and each container can connect to different Oracle Databases without having to rebuild the image.

Hire Node JS Developer from Expert Node JS Development Company

Hire Node JS Developer from Expert Node JS Development Company

NodeJS Development Company-Hire Node JS developer from the most prominent NodeJS development company, Mobiweb and get remarkable Node.js app development services.

Are you looking to hire the most talented and expert Node JS developers for your valuable web application projects and mobile app development projects or you want to migrate application on Node JS framework? Then you have to hire Node JS developer from leading offshore Node JS development company Mobiweb Technologies. We have a team of developers with extensive experience in developing Node JS based applications whether it is web based or mobile app based.

Main Reasons of Using Node JS for Your Web Application Development

Main Reasons of Using Node JS for Your Web Application Development

You have to hire Node JS developer from prestigious and expert Node JS development company Mobiweb Technologies. They are tech enthusiasts with new and latest programming ideas, web development technologies and industry trends.

Node JS is the best JavaScript for utilizing in real-time applications. If you are stressed of using low level web sockets or protocols then with the incredible speed of Node JS you can easily develop real-time applications. According to the business perspective, Node JS is highly advantageous for any online business or business website, so it is very difficult for companies or business owners to avoid Node JS for their web application projects. For the best results in your Node JS development project you must have to hire Node JS developer from the prestigious web development company- Mobiweb Technologies.

Dockerizing a Node.js web application

Dockerizing a Node.js web application

In this article, we will see how to dockerize a Node.js application. Dockerizing a Node.js web application

Originally published by  ganeshmani009 at  cloudnweb.dev

what is docker ?

Firstly, Docker is containerization platform where developers can package the application and run as a container.

In simple words, docker runs each application as a separate environment which shares only the resources such as os, memory, etc.

Virtual Machine vs Docker

Docker and node.js setup

Here, we can find the difference between the docker and virtual machines.

To read more about docker, Docker Docs

we are gonna see how to dockerize a node.js application. before that, docker has to be installed on the machine. Docker Installation

After installing the docker, we need to initialize the node application.

npm init --yes
npm install express body-parser

the first command initializes the package.json file which contains the details about the application and dependencies. the second one install the express and bodyParser

create a file called server.js and paste the following code

'use strict';

const express = require('express');

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
res.send('You have done it !!!!!\n');
});

app.listen(PORT,()=>{
console.log(Running on http://${HOST}:${PORT});
});

this runs the basic express application server. now, we need to create the docker image file. create a file name called Dockerfile and add the following commands

FROM node:8

First we install the node image from the Docker hub to the image

WORKDIR /usr/src/app

Next, we set the /usr/src/app as the working directory in the docker image

COPY package*.json ./
RUN npm install

then copies the package.json from the local machine to docker image. It’s not an efficient way to copy the dependencies from local to docker image.

so we are just copying the package.json and install all the dependencies in the docker image

COPY . .
EXPOSE 8080

CMD [ "npm" , "start" ]

it copies all the source code from local to docker image, binds the app to port 8080 in the docker image. docker image port 8080 can be mapped with local machine port. then we run the command

Your Dockerfile should now look like:

# this install the node image from docker hub
FROM node:8

this is the current working directory in the docker image

WORKDIR /usr/src/app
#copy package.json from local to docker image
COPY package*.json ./
#run npm install commands
RUN npm install
#copy all the files from local directory to docker image
COPY . .
#this port exposed to the docker to map.
EXPOSE 8080

CMD [ "npm" , "start" ]

create a .dockerignore file with the following content:

node_modules
npm-debug.log

now, we need to build our image in the command line as :

$ docker build -t <your username>/node-web-app .

-t flag used to tag a name to image. so, it will be easy to identify with a name instead of id. Note : dot in the end of command is important(else it won’t work)

we could run the image using the following command :

docker run -p 49160:8080 -d <your username>/node-web-app

we can check it using

 curl -i localhost:49160

output should be:

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 23
ETag: W/"17-C2jfoqVpuUrcmNFogd/3pZ5xds8"
Date: Mon, 08 Apr 2019 17:29:12 GMT
Connection: keep-alive

You have done it !!!!!

To read more

https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md

Originally published by  ganeshmani009 at  cloudnweb.dev

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter


Further reading

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Best 50 Nodejs interview questions from Beginners to Advanced in 2019

☞ Node.js 12: The future of server-side JavaScript

☞ Docker for Absolute Beginners

☞ How to debug Node.js in a Docker container?

☞ Docker Containers for Beginners

☞ Deploy Docker Containers With AWS CodePipeline