DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • On-Premises Legacy Oracle Database to PostgreSQL Database as a Service
  • Lessons from Migrating an Oracle Database to AWS RDS
  • Docker Bake: A Modern Approach to Container Building
  • Containerization of a Node.js Service

Trending

  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • Designing AI Multi-Agent Systems in Java
  • Web Crawling for RAG With Crawl4AI
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Connect Your NodeJS App in Docker to Your Oracle Database

How to Connect Your NodeJS App in Docker to Your Oracle Database

No matter the situation, easily connect your NodeJS to your database.

By 
Blaine Carter user avatar
Blaine Carter
·
Updated Sep. 05, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
17.3K Views

Join the DZone community and get the full member experience.

Join For Free

minor-bar-chord-on-guitar

Make Node work for you



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.
You may also like:  Introdcution to Node.js Part One.

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

In a previous post, I walked through how to set up both an ORDS instance and an Oracle XE instance in Docker Containers. Follow through the section showing how to create an Oracle XE Database in a Docker container.

When you followed the steps in that post you should have also 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.


Related Articles

  • Node.js Tutorial for Beginners (Part 1): Intro to Node and Express. 
  • Node.js vs. Django: Is JavaScript Better Than Python? 

Docker (software) Database connection Cloud database Oracle Database Node.js app

Published at DZone with permission of Blaine Carter, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • On-Premises Legacy Oracle Database to PostgreSQL Database as a Service
  • Lessons from Migrating an Oracle Database to AWS RDS
  • Docker Bake: A Modern Approach to Container Building
  • Containerization of a Node.js Service

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!