简体   繁体   中英

ip.address() does not work on aws. How to get the IP address of AWS EC2 programmatically?

I developed a React application with Node/Express backend. It is based on the following starter kit. It works fine on my local machine but when I deploy it on AWS it starts with incorrect IP address.

My config file

    const ip = require('ip')
    server_host : ip.address(),
    server_port : process.env.PORT || 3000,

Running npm start on local machine - works fine and it starts as

    app:bin:server Server is now running at 192.168.1.5:3000.

but when I put it on EC2 (52.72.209.201) and start it doesn't work and I get the logs as

    app:bin:server Server is now running at 172.31.31.141:3000.

If I hardcode the IP address of my instance in the config file it works fine

    server_host : '52.72.209.201',
    server_port : process.env.PORT || 3000,

now it starts and runs fine

    app:bin:server Server is now running at 52.72.209.201:3000.

What can I do to remove hardcoded IP address?

You should be able to get your public IP address from:

or:

You can use curl in a shell script (like your startup script) to get it and for example store in an environment variable or some file on the file system. Or you can use request in Node.

For more info see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM