How to set up pm2 in digital ocean cloud server for MERN Stack? - digital-ocean

I able to set up the pm2 successfully with my MERN Stack application, but when I tried to run pm2 start server.js and it shows status online but I was not able to access my MERN stack application in the browser, but when I run my application without using pm2 npm run dev with Nodemon everything was working fine. Below is my server.js file
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const config = require('config');
const path = require('path');
const devPort = 8080;
// Setup express app
const app = express();
app.use(cors());
app.options('*', cors());
app.use(express.json());
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.Promise = global.Promise;
const db = config.get('MONGODB_URI');
mongoose.connect(db, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
});
mongoose.connection
.once('open', () => console.log('Database connected!'))
.on('error', error => console.log('Could not connect', error));
/*route/api/file is here*/
app.use('/api/user', require('./route/api/user'));
//server static assets in production
if (process.env.NODE_ENV === 'production') {
//set static folder
app.user(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.htm'));
});
}
app.listen(process.env.PORT || devPort, () =>
console.log(`Node JS is running on port ${devPort}`)
);
here is an image of pm2 server.js online in the terminal but I could not access it.
I wondered, is it the problem with the server.js file, please give suggestions.
Thank you for your help.

Setup pm2 config
cd to project folder
Create ecosystem.config.js file for pm2 with the following config
module.exports = {
apps : [{
name : 'APPNAME',
script : './index.js',
env: {
NODE_ENV: 'development'
},
env_production : {
NODE_ENV: 'production'
}
}],
};
Start app's process using pm2
For production : pm2 start --env production
For development : pm2 start --env development
Some basic pm2 commands
Stop App : pm2 stop APPNAME
Start App : pm2 start APPNAME
Monitor App : pm2 monit APPNAME
Delete App : pm2 delete APPNAME
Show list of running pm2 processes : pm2 list
Hope this helps!

Related

Puppeteer-core on the aws-lambda docker image Error: Target closed

I have been working with puppeteer-core on the aws-lambda docker image for a while but I have encountered recently a problem while running it locally.
It is a known old error "Protocol Error: Target closed", but I suddenly encountered the last few days.
I tried many solutions suggested on the threads like this one but so far I haven't been successful.
This is an easy to run simplified version of the code GitHub but I will write it down here too:
async function launchBrowser() {
try {
const puppeteer = require('puppeteer-core');
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
'--no-zygote',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--single-process',
],
headless: true,
ignoreHTTPSErrors: true,
executablePath: '/usr/bin/chromium-browser',
});
return browser;
} catch (error) {
console.log("error",error);
return launchBrowser();
}
}
async function lambdaHandler(event, context) {
let result = null;
console.info(`EVENT ${JSON.stringify(event, null, 2)}`);
const browser = await launchBrowser();
console.info('browser launched');
try{
console.log(await browser.version());
const page = await browser.newPage();
await page.goto(event.url);
result = await page.title();
console.info("Title",result);
}
catch(error){
console.log(error)
}
return result;
}
module.exports = { handler: lambdaHandler };
The docker file:
FROM public.ecr.aws/lambda/nodejs:14
RUN yum install -y amazon-linux-extras
RUN amazon-linux-extras install epel -y
RUN yum install -y chromium
RUN npm install puppeteer-core
COPY src/* ${LAMBDA_TASK_ROOT}
CMD [ "app.handler" ]
It gets stuck on browser.version() and sends that error.
The confusing thing is that when I deployed the code on AWS I didn't have the same issue so I couldn't identify the origin of this sudden change and why the errors are very inconsistent.
I want to also specify that I am working on MacOS Monterey with apple M1.
So if anyone can enlighten that would be very helpful.

detox[3338] DEBUG: [APP_STATUS] Failed to execute the current status query

I try to add detox to my expo application, everthing seams to work fine, but when I try to run the test I get following error message.
detox[3338] DEBUG: [APP_STATUS] Failed to execute the current status query.
firstTest.e2e.ts
const { reloadApp } = require('detox-expo-helpers');
describe('Example', () => {
beforeAll(async () => {
await reloadApp({
permissions: {
location: 'always',
userTracking: 'YES'
}
})
});
it('test', async () => {
await expect(element(by.id('settings'))).toBeVisible()
await element(by.id('settings')).tap()
console.log('success')
})
})
At first I start the expo server with yarn expo start --ios and then run the detox test with yarn detox test -c ios --loglevel trace. The app will be installed and loaded but stucks at the error message. Did any one has an solution?

Running Unit and automation UI tests in one place in Jenkins and receive such Error: Failed to launch the browser process

For now we are execute unit tests together with UI automation and for now unit tests is passing OK, but ui automation receive Error: Failed to launch the browser process!
for now we have Jenkins file for both tests templates
stage('Build npm env and Execute AutomationTests'){
steps {
executeDocker(dockerImage: 'docker.wdf.sap.corp:50000/buildkite/puppeteer:latest', dockerWorkspace: '/home/piper'){
sh 'npm install'
sh 'npm update -g'
sh 'npx browserslist#latest --update-db'
}
}
}
stage('Update Build Badge'){
steps {
script {
def userIdCause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
def userId = userIdCause[0].userId
gitCommit = sh(returnStdout: true, script: 'git rev-parse --short=8 HEAD').trim()
manager.addShortText('User: ' + userId + ' , Commit Sha: ' + gitCommit , "grey", "transparent", "0px", "white")
}
}
}
stage('Build UI Application and Execute UnitTests'){
steps {
executeDocker(dockerImage: 'node:14-stretch', dockerWorkspace: '/home/piper'){
sh 'npm install'
sh 'npm run build-dev'
sh 'npm run test'
stash name: "build", includes: 'dist/**, coverage/**'
}
}
}
also we have separate config files
this one for unit tests
module.exports = {
preset: "#vue/cli-plugin-unit-jest",
collectCoverage: true,
collectCoverageFrom: [
"src/**/*.{js,vue}",
"!src/main.js", // No need to cover bootstrap file
],
}
and this is config file for ui automation
module.exports = {
preset: "#vue/cli-plugin-unit-jest",
collectCoverage: true,
collectCoverageFrom: [
"src/**/*.{js,vue}",
"!src/main.js", // No need to cover bootstrap file
],
}
and setup file for ui automation
import puppeteer from "puppeteer"
jest.setTimeout(60000)
beforeAll(async () => {
global.browser = await puppeteer.launch({
headless: true,
slowMo: 0,
args: ["--disable-setuid-sandbox", "--no-sandbox"],
})
})
afterAll(() => {
global.browser.close()
})

Configuring Blackfire on a base virtual box using Chef

I'm trying to give Blackfire.io (by Sensiolabs) a try to profile an existing PHP application running on a Vagrant machine (with PHP 5.3) on Mac.
I'm using Chef to provision my machine with Blackfire, but when running "vagrant provision" I get the following error:
default: STDERR: The server ID parameter is not set. Please run
blackfire-agent -register to configure it.
..which I already did
This is my Vagrant file:
is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)
Vagrant.configure("2") do |config|
..
config.vm.box = "covex/ubuntu1204-x64"
config.omnibus.chef_version = :latest
config.vm.provision "chef_solo" do |chef|
chef.json = {
:blackfire => {
:'server-id' => "d4860b49-be67-404b-9fa1-b..",
:'server-token' => "c412751f30d6c724033d8408e.."
}
}
chef.add_recipe "blackfire"
end
end
I followed the installation steps on https://blackfire.io/getting-started, except for the Probe paragraph.
Is my Vagrant file wrongly configured, so it can't read the server ID and token? Is the "brew install blackfire-php53" needed for this, if so, is there a way to configure this through my Vagrant file?
Guessing you are using https://supermarket.chef.io/cookbooks/blackfire
You missed the agent node in the config tree
{
"blackfire" => {
"agent" => {
"server-id" => "your server-id",
"server-token" => "your server-token",
}
}
}

Gradle: How do I stop Jetty if JMeter test failed

How do I stop Jetty if JMeter test failed?
My Gradle script:
apply plugin: 'jetty'
apply plugin: 'jmeter'
jmeterRun {
doFirst() {
jettyRunWar.httpPort = 8080 // Port for test
println "Starting Jetty on port:" + jettyRunWar.httpPort
jettyRunWar.daemon = true
jettyRunWar.execute()
}
doLast() {
println "Stopping Jetty"
jettyStopWar.stopPort = 8091 // Port for stop signal
jettyStopWar.stopKey = 'stopKey'
jettyStopWar.execute()
}
jmeterTestFiles = [
file("src/test/jmeter/Tests.jmx")
]
}
You can use the method finalizedBy to ensure that Jetty is stopped no matter whether JMeter runs successfully or fails.
jmeterRun {
dependsOn jettyRunWar
finalizedBy jettyStopWar
}
Try the below settings:
In doFirst()
jettyRunWar.stopPort = 8090
jettyRunWar.stopKey = 'stopKey'
In doLast()
jettyStop.stopPort = 8090
jettyStop.stopKey = 'stopKey'
Not sure if it's a bug related to this Link or that you just need to specify a stopPort for jetty to be listening on.
I was having problems stopping jetty after running the jettyRunWar task in intelliJ but have those 4 settings in my build.gradle allowed me to stop jetty by running the jettyStop task.