MongoDB allow access only from local server
You have to enable MongoDB access control. This uses a bindIp value in the mongod.conf file that by default listens to connections locally (e.g. bindIp:127.0.0.1 or with another local address, bindIP:127.0.0.1,10.0.0.10).

For that, you will need to create an admin or root user by doing this:

use admin
db.createUser(
  {
    user: "root",
    pwd: "abc123",
    roles: [ { role: "root", db: "admin" } ]
  }
)


Something similar you will need to do to create a user for your application:

use appDatabase
db.createUser(
  {
    user: "appUser",
    pwd: "appUserPassword",
    roles: [ { role: "readWrite", db: "appDatabase" } ]
  }
)


Then, in your mongod.conf file (in a CentOS server is located at /etc/mongod.conf), do the following:


Uncomment 'security'. 
Add below it 'authorization: enable' (keep authentication commented out). 
Make sure the bindIp value is set to 127.0.0.1


Then, when logged onto your server, if you need to connect to your MongoDB instance, do that with the admin/root user you just created:

mongo -u root -p --authenticationDatabase admin


You should also make sure you can successfully log onto mongo with your appUser:

mongo -u appUser -p --authenticationDatabase appDatabase


From your application, you will need to connect with an URL similar to this one:

mongodb://appUser:appUserPassword@localhost:27017/appDatabase?authSource=appDatabase


Reference: 
MongoDB - Enable Authentication | 
MongoDB - Configuration File Options