You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

1. Install Node.js and npm on Ubuntu
  • 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
    
2. Create a Basic Node.js API Server for Database Queries

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 -y
    
  • Install the required packages:

    npm install express mysql2 cors
    
    • express: The web framework to build the server
    • mysql2: A fast, reliable MySQL driver for Node.js
    • cors: Allows cross-origin requests (so your Android app can call the server without CORS errors)
  • Create a server.js file 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_ADDRESS and database credentials) with your actual details.

3. Configure Firewall to Allow Traffic

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
4. Test the Server
  • 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:
    curl http://YOUR_STATIC_IP:3000/api/users
    
    You should see your database data returned as JSON if everything works.
5. Keep the Server Running in the Background

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
    
Troubleshooting Tips
  • 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)
  • If database connections fail:
    • Ensure your database user has permission to connect from localhost
    • Double-check your database credentials are correct

内容的提问来源于stack exchange,提问作者Pronoy999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:04:53