process.env.VARIABLE is undefined in webpack/docker/heroku deployment - node.js

I am having some issues getting my app to read the heroku environment variables. The application itself is a node.js react/redux web application ran with webpack-dev-server, deployed in a Docker container which is hosted on Heroku.
I'm setting the variables in a config.js file, which are to be used through the app:
module.exports = {
baseUri: process.env.BASE_URI || "http://localhost:8000",
baseApiUri: process.env.BASE_API_URI || "http://localhost:8080",
port: process.env.PORT || 8000
}
In my index.tsx file I am trying to make a simple get request to the baseApiUri, but am finding that it is defaulting to localhost even though I have these variables as settings in Heroku.
I am getting these results both:
locally when I run
set BASE_URI='http://test.com/'&&set BASE_API_URI='http://testapi.com/'&&set PORT=5000&&webpack-dev-server --host 0.0.0.0
remotely when I run:
webpack-dev-server --host 0.0.0.0

Related

Error: The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable

I'm trying to deploy my API to Cloud Run but I'm stuck with this error
ERROR: (gcloud.run.deploy) The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable. Logs for this revision might contain more information.
This is my Dockerfile
FROM node:lts
WORKDIR /src
COPY package.json package*.json ./
RUN npm install --omit=dev
COPY . .
CMD [ "npm", "execute" ]
This are my package.json scripts
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "env-cmd -x -f ./src/config/env/.env.local nodemon ./src/index.js",
"deploy:dev": "env-cmd -x -f ./src/config/env/.env.dev ./deploy.sh",
"execute": "env-cmd -x -f ./src/config/env/.env.dev node ./src/index.js"
},
This is my index.js
const api = require("../src/config/config");
const port = process.env.PORT || 8080;
console.log("Puerto => ", port);
api.listen(port, () => {
console.log(`Rest API started succesfully`);
});
This is my config file (I'm working with firebase)
const express = require("express");
// Config
const api = express();
api.use(express.json());
// Routes
api.use(require("../routes/start.routes.js"));
module.exports = api;
And I have a .env file with the PORT variable
PORT=8080
And these are the commands I execute
gcloud builds submit --tag gcr.io/$GOOGLE_PROJECT_ID/api --project=$GOOGLE_PROJECT_ID
gcloud run deploy api --image gcr.io/$GOOGLE_PROJECT_ID/api --port 8080 --platform managed --region us-central1 --allow-unauthenticated --project=$GOOGLE_PROJECT_ID
I have followed every tip about similar questions but none has worked for me
I checked logs and they only expose the description I referred in the beginning.
I try to run my project locally with Cloud Run Emulator, it does not work but I don't get enough info to figure out what's wrong. I don't even understand why in the docker container I see several ports except 8080 which is the one the app should listen on and then says the deploy process failed
I'm using windows 11
My API works fine locally if I run npm run start
The error clearly does indicate that there is an issue with the specific defined incoming HTTP requests ports and the container is failing to listen on the expected port.The official document Cloud Run container contract has these mentioned to meet these requirements in order to operate properly.
In Node.js ,your js should define as below:
const port = process.env.PORT || 8080; app.listen(port, () => { console.log('Hello listening port', port); });
You may check if your container is listening on all network interfaces once by denoting port as 0.0.0.0 and see if that works.You may also want to confirm if your container image is compiled for 64-bit Linux as expected by the container runtime contract.
You need to troubleshoot the issue
Check the logs of your Cloud Run service using the command in cloudshell
gcloud logs read --project $GOOGLE_PROJECT_ID --service api --limit 100
//You can adjust the --limit flag to show more or fewer log entries.
2.Check the logs of your container If there is any problem with the container itself, you will get using that command
docker run -p 8080:8080 gcr.io/$GOOGLE_PROJECT_ID/api
that command starts your container and map port 8080 inside the container to your local machine's port 8080. Access your app at http://localhost:8080. Check the console output for any errors with the container.
Check your Cloud Run configuration
Check your application code
in your index.js file Make sure the api.listen() function is using a port variable that is set to the value of the PORT environment variable:
const port = process.env.PORT || 8080;
api.listen(port, () => {
console.log(`Rest API started successfully`);
});
5 check your firewall settings
some times firewall blocks traffic to port 8080.
you can check the firewall rules in the Google Cloud Console
using that step you find the issues and if you can't find the issue then reach out to the Cloud Run support team for further assistance.

Heroku + Node.js: Web process failed to bind to $PORT within 60 seconds of launch

I built a Node.js/Express Web Api. I want to deploy it on Heroku. It works fine on local but when I deploy it I get the following error:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
index.js
app.listen(process.env.PORT || 3000, () => {
console.log(`app running on ${process.env.PORT}`);
});
.env
PORT=3000
I have configured the PORT variable on Heroku -> Settings ->Config Vars section. However it didn't solve my problem.
Additionally, when I look up the application logs on Heroku, the callback function on the listen() method, outputs the following:
2022-07-15T20:06:19.268954+00:00 app[web.1]: app running on undefined
2022-07-15T20:06:20.230943+00:00 app[web.1]: connected to db
connected to db output came from mongodb connection. My app also gets the mongodb credentials from .env file and it works fine. But why I can't get PORT variable and it returns undefined?
This is a duplicate of this question and the answer is - PORT variable is provided by Heroku and you can't set it.
I removed the PORT variable either on .env file or Config Vars on Heroku.
And I change the way to call the PORT variable to not conflict with Heroku's default PORT.
index.js
let port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`app running on ${port} `);
});
App runs on 3000 port in localhost and Heroku's default port in server now.

Deploy FeathersJS App on Heroku

I'm trying to deploy my feathersjs web app on heroku, and since feathers is simply an express wrapper I thought it was like deploy an ordinary node app. I got the "npm start" script on my package.json, I added heroku remote to my git repo and when I push heroku run "yarn install" and the "npm start" script. But just when the app start, an error occurs:
heroku logs
I can't figure out what happen, any suggestions?
Maybe I could dockerize my app, someone could help me to find the proper implementation?
Thanks everybody
It is the same as Express but the generated application will by default use feathers-configuration to pull in your application settings. From the error message it looks like you are not providing a proper NODE_ENV environment variable which has to be set to production when deploying to Heroku.
Working port of feathers-chat app to Heroku PostgreSQL via Sequelize
I got a port of the hello world https://github.com/feathersjs/feathers-chat running on Heroku right now!
source: https://github.com/cirosantilli/feathers-chat/tree/sequelize-pg
live until it breaks: https://cirosantilli-feathersjs-chat.herokuapp.com/
Key source changes
Set 'postgres' to the DATABASE_URL environment variable config/production.json:
+ "postgres": "DATABASE_URL"
Heroku also exports PORT which was also already in that file before my patch.
Pass dialiectOptions to the DB connection as per: Can't connect to heroku postgresql database from local node app with sequelize
+ const sequelize = new Sequelize(connectionString, {
+ dialect: 'postgres',
+ logging: false,
+ define: {
+ freezeTableName: true
+ },
+ dialectOptions: {
+ // https://stackoverflow.com/questions/27687546/cant-connect-to-heroku-postgresql-database-from-local-node-app-with-sequelize
+ // https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js
+ // https://stackoverflow.com/questions/58965011/sequelizeconnectionerror-self-signed-certificate
+ ssl: {
+ require: true,
+ rejectUnauthorized: false
+ }
+ }
+ });
Key Heroku settings
enable the PostgreSQL Heroku add-on with:
heroku addons:create heroku-postgresql:hobby-dev-
This automatically sets the DATABASE_URL environment variable for us.
in config/production.json edit host to your correct value
in the Heroku app Settings, set the NODE_ENV environment variable to production
Bibliography:
https://github.com/feathersjs/feathers/issues/1647
try set "NODE_CONFIG_DIR" to "app/config/"

Signalmaster on https: ERR_CONNECTION_REFUSED

I have an ember project using Signalmaster. In the config/environment.js I have the following:
if (environment === 'production') {
ENV.SIGNALMASTER = {
HOST: 'https://localhost:8890',
PORT: '8890',
FORCE_CONNECTION: true
};
On my server I have signalmaster running at https://localhost:8890 (in the development.json and production.json files in the config directory for signalmaster I have secure set to true, and in the server.js file for signalmaster I've put in the location of my SSL certificate and key, as is required for running it on https) - when running "node server.js" I get the following:
signal master is running at: https://localhost:8890
Running "netstat -lnp" also shows a process running on port 8890. However when I use the app I get errors like this:
GET https://localhost:8890/socket.io/?EIO=3&transport=polling&t=LjG8--J net::ERR_CONNECTION_REFUSED
I am using socket.io version 1.3.7.
Instead of having the host as https://localhost:8890, seems it had to be https://[domain.com]:8890

How do I make Openshift to use Express 4, instead of its installed Express 3?

I developed my Nodejs Express app locally using Express 4 and it works as expected on my computer. I then git the whole app up to Openshift. When I try to run it Openshift returns"503 Service Unavailable". If I ssh into my base Node cartridge and do "express -V" it returns version 3.2.5. I get the same version 3.2.5 if I go into my app folder at app-root/repo and run "express -V".
So clearly my Express 4 which was included in the git upload in my app's node_modules is not being used. What is the solution to use Express 4 as required by my app?
Ideas are- remove Openshift's version of Express 3, force Openshift to use my Express 4 in my app area, upgrade Openshift's Express 3 to Express 4. I cannot figure out how to do any of those and I have researched this.
Here's how to troubleshoot:
ssh into your cartridge
cd into the app-root/repo directory
run grep version ./node_modules/express/package.json
you should see a version based on your package.json dependency
verify your package.json has a scripts section containing a start command that just runs your app with something like node ./server.js (server.js being whatever file you coded your main app start script in). You don't need the express command line program to launch an express server. It's for setting up new project boilerplate and other ancillary tasks.
To see the version of express running within your app, you can add this code to your server.js (or equivalent) file: console.log(require("express/package").version);
Look at this project to know how to integrate openshift with express4
Its a simple example .
https://github.com/master-atul/openshift-express4
try this
rhc ssh
cd app-root/repo
npm start
also edit the ./bin/www
var port = normalizePort(process.env.OPENSHIFT_NODEJS_PORT || '8080');
var ip = process.env.OPENSHIFT_NODEJS_IP;
if (typeof ip === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
ip = "127.0.0.1";
};
//app.set('ip', port);
app.set('port', port);
var server = http.createServer(app);
server.listen(port, ip);
server.on('error', onError);
server.on('listening', onListening);
you can follow step:
copy all content bin/www and replace all content in file server.js:
Change some content at server.js:
from
`var port = normalizePort(process.env.PORT || '3000');`
to
var port = normalizePort(process.env.OPENSHIFT_NODEJS_PORT || '3000');
Add line:
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
from
server.listen(port);
to
server.listen(port, ip);
Add more to package.json
from
"scripts": {
"start": "node bin/www"
},
to
"scripts": {
"start": "node server.js"
},
Add line:
"main": "server.js",
Use npm install --save module-name for npm install
create file .gitignore with content:
node_modules
on local run node server.js to start server with address localhost:3000
upload to openshift:
git add .
git commit -m "First update new server version"
git push
Browser: domain-appname.rhcloud.com

Resources