Ubuntu系统部署Node.js服务器,替代PHP实现Android数据库查询
Got it, let's walk through setting up a Node.js server on Ubuntu to replace PHP for your Android app's database queries, and get it running on a static IP. Here's a step-by-step guide that's worked for me and many others:
- First, update your package list to ensure you’re getting the latest software versions:
sudo apt update && sudo apt upgrade -y - Install Node.js and npm via the official NodeSource repository (this gives you a more recent version than Ubuntu’s default repo):
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - sudo apt install -y nodejs - Verify the installation was successful by checking the versions:
node --version npm --version
I’d recommend using Express.js—it’s lightweight and perfect for building APIs that your Android app can call. We’ll pair it with MySQL (a common choice for mobile apps) but you can swap it for PostgreSQL or MongoDB if needed.
Create a new project folder and initialize npm:
mkdir node-db-server && cd node-db-server npm init -yInstall the required packages:
npm install express mysql2 corsexpress: The web framework to build the servermysql2: A fast, reliable MySQL driver for Node.jscors: Allows cross-origin requests (so your Android app can call the server without CORS errors)
Create a
server.jsfile with this example code:const express = require('express'); const mysql = require('mysql2'); const cors = require('cors'); const app = express(); const port = 3000; // Use any port you prefer—just remember to open it in your firewall const staticIp = 'YOUR_STATIC_IP_ADDRESS'; // Replace with your actual static IP // Enable CORS for all requests (restrict to specific domains if needed) app.use(cors()); // Parse JSON request bodies (required for POST requests from Android) app.use(express.json()); // Create a database connection pool (better for performance than a single connection) const db = mysql.createPool({ host: 'localhost', // Use this if your database is on the same server user: 'YOUR_DB_USER', // Replace with your database username password: 'YOUR_DB_PASSWORD', // Replace with your database password database: 'YOUR_DB_NAME' // Replace with your target database name }); // Example endpoint: Fetch all entries from a "users" table app.get('/api/users', (req, res) => { const query = 'SELECT * FROM users'; db.query(query, (err, results) => { if (err) { console.error('Database query error:', err); return res.status(500).json({ error: 'Failed to fetch data' }); } res.json(results); }); }); // Example endpoint: Add a new user via POST request app.post('/api/users', (req, res) => { const { name, email } = req.body; const query = 'INSERT INTO users (name, email) VALUES (?, ?)'; db.query(query, [name, email], (err, results) => { if (err) { console.error('Database insert error:', err); return res.status(500).json({ error: 'Failed to add user' }); } res.json({ message: 'User added successfully', userId: results.insertId }); }); }); // Start the server bound to your static IP app.listen(port, staticIp, () => { console.log(`Server running at http://${staticIp}:${port}/`); });Don’t forget to replace all placeholder values (like
YOUR_STATIC_IP_ADDRESSand database credentials) with your actual details.
Ubuntu uses ufw (Uncomplicated Firewall) by default. You need to open the port your server uses to accept incoming requests:
sudo ufw allow 3000/tcp sudo ufw enable # Enable the firewall if it's not already active
Verify the rule is added:
sudo ufw status
- Start the server locally first:
node server.js - From your Android device (or another machine on the same network), test the endpoint using a tool like Postman, curl, or even a browser:
You should see your database data returned as JSON if everything works.curl http://YOUR_STATIC_IP:3000/api/users
If you close your terminal, the server will stop. Use pm2 (a Node.js process manager) to keep it running 24/7:
- Install pm2 globally:
sudo npm install -g pm2 - Start the server with pm2:
pm2 start server.js --name "db-api-server" - Set pm2 to start on system boot (so the server restarts after a reboot):
pm2 startup ubuntu pm2 save - Check the server status anytime:
pm2 status
- If you can’t connect from your Android device:
- Double-check your static IP is correctly set in
server.js - Confirm the firewall port is open
- Verify your router isn’t blocking incoming traffic (you may need to set up port forwarding if your server is behind a router)
- Double-check your static IP is correctly set in
- If database connections fail:
- Ensure your database user has permission to connect from
localhost - Double-check your database credentials are correct
- Ensure your database user has permission to connect from
内容的提问来源于stack exchange,提问作者Pronoy999

