1

I am new to linux and AWS. I have a node.js server running on an EC2 instance. I am running the following command to keep it running endlessly and on port 80:

 $ sudo node app.js &

Now when I run it using sudo my node application will not find any of the environment variables.

I need to be able to set environment variable USER, PASSWORD, and an IP to connect to my database. I have tried countless commands and only managed to set 1 environment variable but it gets deleted when I set a new variable.

SOLUTION

I found what I was looking for thanks to the example Jeff Schaller gave below. I tried it exactly as it was but I'm not sure why it didn't work, I ended up learning a bit on shellscripts.

First I ran $ vim runapp.sh. Then I added the following code :

#!/bin/sh
Clear
export USER="Username"
export PASSWORD="Password"
export IP="1.1.1.1"
Node ./bin/www

After I saved the file, I ran $ chmod +x runapp.sh

Finally I ran $ sudo ./runapp.sh & and it ran perfectly.

If I should not be doing this or if there is an error or a better and safer way of doing it let me know so that I can fix it eventually.

2
  • You might try: sudo USER=... PASSWORD=... node app.js. This sets the environment variables just for the forked process, and hopefully in a way that sudo will allow.
    – Castaglia
    Apr 18, 2016 at 3:06
  • Just wrap the vars in a shell script, then sudo the script.
    – Jeff Schaller
    Apr 18, 2016 at 3:19

1 Answer 1

1

Create a file like the following:

#!/bin/sh
USER=u PASSWORD=p IP=10.10.10.10 node app.js

... or ...

#!/bin/sh
USER=u; export USER
PASSWORD=p; export PASSWORD
IP=10.10.10.10; export IP
node app.js

... where you put your own values in there instead of "u", "p", and "10.10.10.10". Save the file as, say, runapp, then make it executable with chmod u+x runapp, then you run it:

sudo ./runapp &
1
  • As a side note, unless you have a nopasswd flag in your sudo config, I'd recommend running something like sudo -l before trying to run a sudo command in the background -- just so that you can send your password to the sudo prompt.
    – Jeff Schaller
    Apr 19, 2016 at 0:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .