Node.js+PostgreSQL+Docker环境下npm run dev未创建DB表求助
问题:PostgreSQL表未自动创建,执行npm run dev无预期表生成
已成功连接PostgreSQL数据库,但执行npm run dev时,预期自动创建的clients、trainers表并未生成。
已尝试的操作
- 在
initDB.js中添加CREATE TABLE IF NOT EXISTS语句确保表创建 - 确认PostgreSQL数据库可正常访问且连接正确
- 使用Docker的
--no-cache选项避免缓存干扰 - 查看docker-compose日志,未发现表未创建的相关错误信息
期望
每次执行npm run dev时,若所需表(如clients、trainers)不存在则自动创建。
相关代码文件
server.js
dotenv.config(); const app = express(); const port = process.env.PORT || 5000; app.use(cors()); app.use(express.json()); const startServer = async () => { try { await initDB(); console.log("✅ Database initialized"); setupRoutes(app); app.get('/', (req, res) => { res.send('Welcome to Tilo Backend!') }); app.listen(port, () => { console.log(`🎉 Server is running on port ${port} 🎉`); }); } catch (err) { console.error("❌ Error during server startup", err); } }; startServer();
initDB.js
export const initDB = async () => { try { console.log("✅ Initializing database..."); await pool.query(` CREATE TABLE IF NOT EXISTS clients ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, username VARCHAR(100) NOT NULL, password VARCHAR(255) NOT NULL ); `); console.log("✅ Created 'clients' table if it didn't exist"); await pool.query(` CREATE TABLE IF NOT EXISTS trainers ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, username VARCHAR(100) NOT NULL, password VARCHAR(255) NOT NULL ); `); console.log("✅ Created 'trainers' table if it didn't exist"); } catch (err) { console.error("❌ Failed to init DB", err); throw err; } };
docker-compose.yml
services: app: build: . container_name: tilo_backend ports: - "5001:5000" environment: - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_HOST=${DB_HOST} - DB_PORT=${DB_PORT} - DB_NAME=${DB_NAME} - JWT_SECRET=${JWT_SECRET} depends_on: - db networks: - tilo-network volumes: - .:/usr/src/app command: npm run start-server db: image: postgres:14 container_name: tilo-db environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} ports: - "5432:5432" networks: - tilo-network volumes: - postgres_data:/var/lib/postgresql/data restart: always networks: tilo-network: driver: bridge volumes: postgres_data: {}
Dockerfile
# Use official Node.js image as the base image FROM node:22 # Set the working directory inside the container WORKDIR /usr/src/app # Copy the package.json and package-lock.json (if present) into the container COPY package*.json ./ # Install dependencies RUN npm install # Copy the rest of the application files into the container COPY . . # Command to run the app CMD ["npm", "run", "dev"]
package.json
{ "name": "tilo-backend", "version": "1.0.0", "main": "index.js", "type": "module", "scripts": { "dev": "docker-compose build --no-cache && docker-compose up -d && npm run start-server", "start-server": "nodemon src/server.js", "stop": "docker-compose down" }, "keywords": [], "author": "", "license": "ISC", "description": "", "dependencies": { "bcrypt": "^5.1.1", "bcryptjs": "^3.0.2", "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^5.1.0", "jsonwebtoken": "^9.0.2", "pg": "^8.14.1" }, "devDependencies": { "@types/module-alias": "^2.0.4", "@types/node": "^22.14.0", "nodemon": "^3.1.9" } }
内容的提问来源于stack exchange,提问作者Bohdan Romanovich
相关产品推荐
相关产品推荐

