Windows Server 2012中PostgreSQL 10无法后台运行求助
Hey there, I get exactly what you're dealing with—running PostgreSQL via pg_ctl in cmd works until you close the window, which kills the server. That's because the PostgreSQL process is tied directly to the cmd session you launched it from. To get it running in the background like a proper system service (just like Linux's sudo service postgres start), here are the best solutions:
Option 1: Install PostgreSQL as a Windows Service (Recommended)
This is the standard, long-term fix. Services run independently of user sessions, so they'll keep running even if you log out or close all cmd windows. Plus, you can set it to auto-start on server boot.
- Open cmd as Administrator (right-click cmd.exe and select "Run as administrator"—you need elevated permissions to install a system service).
- Run this command to register the service:
pg_ctl register -N "PostgreSQL 10" -D "\My postgres path\10\data"-N "PostgreSQL 10"sets a friendly name for the service (feel free to tweak this, just be consistent with later commands).-Dpoints to your PostgreSQL data directory—keep the path wrapped in quotes if it includes spaces, like you already are doing.
- Now you can manage the service using Windows standard commands:
- Start the service:
net start "PostgreSQL 10" - Stop the service:
net stop "PostgreSQL 10" - Set it to auto-start on server boot:
Either openservices.msc(type it in cmd or the start menu), find "PostgreSQL 10", right-click > Properties > Startup type > Auto.
Or use this command:
Note: There's a space aftersc config "PostgreSQL 10" start= autostart=—that's required for thesccommand to work correctly.
- Start the service:
Option 2: Temporary Background Run (Not Recommended for Production)
If you just need a quick temporary fix without installing a service, you can launch pg_ctl in the background using the start /B command:
start /B pg_ctl -D "\My postgres path\10\data" start
This will run the server without tying it directly to your cmd window, but warning: if you log out of your Windows session, the process will still terminate. This is only good for short-term testing, not for persistent production use.
Why Your Original Command Didn't Work
When you run pg_ctl start directly in cmd, PostgreSQL runs as a child process of the cmd window. Windows automatically terminates all child processes when the parent cmd window is closed. Services, on the other hand, run in the system's background session, so they're completely independent of user windows or sessions.
内容的提问来源于stack exchange,提问作者Frank Liao

