Search code examples
mongodbgoogle-compute-enginegoogle-cloud-platformstartupsudo

Running mongoDB on startup on Google Compute Engine instance


I have set up Mongo to run on a GCE instance.

At first I was working in / and launching mongo with sudo mongod, but reasonably it prints some warning about that:

WARNING: You are running this process as the root user, which is not recommended.

So I moved everything to /home/my_google_account, and I can just get in through SSH and run mongod.

Now I’d like to have some actions, including mongod, run at startup. From my understanding, the right way to do this is to use Google startup scripts: from the console you can provide a script like the following as a metadata key-value pair:

#! /bin/bash
apt-get update
mongod -f /home/my_google_account/mongod.conf

It works, but as Google says, this is executed as root:

The instance always executes startup scripts as root, and only executes those scripts after it creates any new users whose SSH keys are included in the instance metadata.

So the mongod process is run with root privileges and I still get the warning that I had originally:

WARNING: You are running this process as the root user, which is not recommended.

What should I do?

Is there a way for a startup script not to run as root? Or should I just work in / with sudos and ignore the warning at all? Everybody seems to suggest that you should work in your user’s home folder, get the necessary permissions, and run mongod with your privileges. But then the startup script will run as root anyway!


Solution

  • try this - add a user to your persistent disk -

    useradd -ms /bin/bash mongouser
    #replace /data/db with your data location
    chown -R mongouser /data/db
    

    add this to your starup script

    apt-get update
    sudo mongouser -c 'mongod -f /home/my_google_account/mongod.conf'