OpenShift is an excellent platform for hosting Nodejs applications. And, taking advantage of OpenShift's free hosting, or automated build and scaling features, usually only requires one or two small changes to your code.
This post answers the question, "What makes a Nodejs application OpenShift-compatible?", in two simple steps:
Step 1: Include a package.json file
All nodejs applications should include a package.json
file in the root of their project. OpenShift and npm are both configured to check your (scripts.start
and main
) fields for information on how to launch your server:
"scripts": {
"start": "node server.js"
},
"main": "server.js"
Also, make sure to document your project's npm module dependencies in the dependencies
section to ensure that any missing deps can be automatically resolved during the application's automated build phase.
Using npm install
with the --save
flag will help keep your project's package.json
file up to date as you build:
npm install --save PACKAGE_NAME
As usual, local development environments should be initialized by running npm install
followed by npm start
.
Step 2: Read Configuration Details from the System Environment
OpenShift's Node.js cartridge automatically publishes server connection information to your application's environment via the following environment variables: OPENSHIFT_NODEJS_PORT
and OPENSHIFT_NODEJS_IP
Include a small check to test for the presence of these configuration strings to ensure your project's portability:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
server.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", port " + server_port )
});
This example shows how to quickly check for OpenShift-provided configuration strings while providing sensible default values for local development purposes.
MongoDB users should include some additional checks for environment-supplied credentials:
//provide a sensible default for local development
mongodb_connection_string = 'mongodb://127.0.0.1:27017/' + db_name;
//take advantage of openshift env vars when available:
if(process.env.OPENSHIFT_MONGODB_DB_URL){
mongodb_connection_string = process.env.OPENSHIFT_MONGODB_DB_URL + db_name;
}
Modules like config-chain can also be useful for normalizing this information down into a single variable, helping to provide a consistent interface for all remaining code references.
Additional application keys and secrets can be abstracted from your code using the same technique:
rhc env set GA_TRACKER=UA-579081
rhc env set SECRET_KEY=0P3N_S0URC3
rhc env list
More notes on using environment variables are available in our post on using external services like RedisCloud
That's it! -- If you have committed the changes from our first two steps, your application should now be ready to run on OpenShift.
Now, Document Your Process!
You can spin up a fresh copy of your publicly-hosted nodejs source from the terminal, using our rhc
command-line tool:
rhc app create YOUR_APP_NAME nodejs-0.10 --from-code=http://github.com/USER_NAME/REPO_NAME.git
Or, launch a new instance of your app right from your browser by providing your project's source repository url during the configuration step of OpenShift's web-based app creation process.
The source url and list of service dependencies can also be encoded in a link, allowing you to offer a guided application launching workflow to new users, coworkers, or anyone else who would like to quickly spin up fresh hosted copies of your app in a few simple clicks.
Our post on using GitHub-style Ribbons to Launch applications is a nice follow-up for open source project maintainers that would like to encourage end-users, and community members to spin up their own clones from an existing hosted app.
Regardless of which process you choose, make sure to document it in your project's README
file for others to follow.
What's Next?
- Read Nodejs Hosting: 10 Reasons to Deploy on OpenShift
- Learn more about Scaling Nodejs on OpenShift
- Extend your projects with pluggable cartridge-based services (MongoDB, PostgreSQL, Jenkins)
- Find out how to setup Domain Names and SSL for OpenShift-hosted applications
- Sign up for free access to OpenShift Online
{{cta('1ba92822-e866-48f0-8a92-ade9f0c3b6ca')}}
Sobre el autor
Más similar
Navegar por canal
Automatización
Las últimas novedades en la automatización de la TI para los equipos, la tecnología y los entornos
Inteligencia artificial
Descubra las actualizaciones en las plataformas que permiten a los clientes ejecutar cargas de trabajo de inteligecia artificial en cualquier lugar
Nube híbrida abierta
Vea como construimos un futuro flexible con la nube híbrida
Seguridad
Vea las últimas novedades sobre cómo reducimos los riesgos en entornos y tecnologías
Edge computing
Conozca las actualizaciones en las plataformas que simplifican las operaciones en el edge
Infraestructura
Vea las últimas novedades sobre la plataforma Linux empresarial líder en el mundo
Aplicaciones
Conozca nuestras soluciones para abordar los desafíos más complejos de las aplicaciones
Programas originales
Vea historias divertidas de creadores y líderes en tecnología empresarial
Productos
- Red Hat Enterprise Linux
- Red Hat OpenShift
- Red Hat Ansible Automation Platform
- Servicios de nube
- Ver todos los productos
Herramientas
- Training y Certificación
- Mi cuenta
- Soporte al cliente
- Recursos para desarrolladores
- Busque un partner
- Red Hat Ecosystem Catalog
- Calculador de valor Red Hat
- Documentación
Realice pruebas, compras y ventas
Comunicarse
- Comuníquese con la oficina de ventas
- Comuníquese con el servicio al cliente
- Comuníquese con Red Hat Training
- Redes sociales
Acerca de Red Hat
Somos el proveedor líder a nivel mundial de soluciones empresariales de código abierto, incluyendo Linux, cloud, contenedores y Kubernetes. Ofrecemos soluciones reforzadas, las cuales permiten que las empresas trabajen en distintas plataformas y entornos con facilidad, desde el centro de datos principal hasta el extremo de la red.
Seleccionar idioma
Red Hat legal and privacy links
- Acerca de Red Hat
- Oportunidades de empleo
- Eventos
- Sedes
- Póngase en contacto con Red Hat
- Blog de Red Hat
- Diversidad, igualdad e inclusión
- Cool Stuff Store
- Red Hat Summit