我可以在同一台电脑上运行两个web服务器吗?
我刚发现其实可以用Python写一个非常简单的网页服务器。我现在已经在这台机器上安装了一个Apache网页服务器,我想试试用Python做的这个网页服务器。但是我有点担心,如果我同时运行这两个服务器,会不会出现什么冲突。我是说,当客户端发出请求时,这两个网页服务器会怎么“决定”谁来处理这个请求呢?
7 个回答
一个网页服务器是绑定在特定的端口上的。通常情况下,这个端口是80。如果没有特别指定端口,浏览器默认会尝试连接这个端口。
你可以让你的备用服务器运行在不同的端口上(比如8080或8081,这些都是常用的备用端口,但你可以选择其他的)。
这样就可以避免冲突。所有发送到80端口的请求都会到达你原来的服务器,而发送到8080(或者你选择的其他端口)的请求就会到达你简单的Python服务器。
要访问你的其他服务器,可以使用这样的网址:
如果你真的想要运行不同的服务器来测试服务器软件,可以看看其他的回答,不过……
听起来你是个开发者,而不是系统管理员,对吧?所以,我觉得你其实只是想在同一台电脑上运行Python和PHP的网站。请原谅我可能理解错了你的问题,但这个设置可以让我在同一台电脑上用同一个端口(端口80)通过一个服务器Apache来运行这两种网站。
我在我的 /etc/hosts 文件(在Windows上是 C:\Windows\System32\drivers\etc\hosts)里添加新的条目,并把它们指向127.0.0.1:
127.0.0.1 localhost
# development projects
127.0.0.1 somephpsite.com.local
127.0.0.1 www.somephpsite.com.local
127.0.0.1 otherpythonsite.com.local
127.0.0.1 www.otherpythonsite.com.local
然后在Apache里,我为每个网站添加虚拟主机(VirtualHosts):
<VirtualHost *:80>
DocumentRoot "/Library/WebServer/Documents"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
<Directory "/Users/Robert/Projects/SomeSite/somephpsite.com">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from all
</Directory>
DocumentRoot "/Users/Robert/Projects/SomeSite/somephpsite.com"
ServerName somephpsite.com.local
ServerAlias www.somephpsite.com.local
ErrorLog "/Users/Robert/Projects/SomeSite/error.log"
CustomLog "/Users/Robert/Projects/SomeSite/access.log" common
</VirtualHost>
<VirtualHost *:80>
<Directory "/Users/Robert/Projects/OtherSite/otherpythonsite.com">
Order allow,deny
Allow from all
</Directory>
DocumentRoot "/Users/Robert/Projects/OtherSite/otherpythonsite.com/static"
Alias /(.*(\.css|\.gif|\.ico|\.jpg|\.js|\.pdf|\.txt)) /Users/Robert/Projects/OtherSite/otherpythonsite.com/static/$1
WSGIScriptAlias / /Users/Robert/Projects/OtherSite/otherpythonsite.com/wsgi.py
ServerName otherpythonsite.com.local
ServerAlias www.otherpythonsite.com.local
ErrorLog "/Users/Robert/Projects/OtherSite/error.log"
CustomLog "/Users/Robert/Projects/OtherSite/access.log" common
</VirtualHost>
这样,PHP网站就像往常一样在 DocumentRoot
里运行。而Python网站则通过WSGI运行。它们都在Apache里运行。然后为了测试,我只需要在我使用的浏览器里加上“.local”就可以访问我本地的副本了。
让它们监听不同的端口,这样就没问题了。
默认的网页端口是80。当你在浏览器中打开一个网址而不指定端口时,默认会使用80端口。
你可以把你的网页服务器设置成监听其他端口,但这样你在网址中也需要明确指定这个端口:
http://localhost:8080
选择端口时,要注意这个特定的端口号不能被你电脑上已经安装并运行的软件占用。否则,正如你猜的那样,就会出现冲突。
附言:就在几天前,我在重新安装时发现IIS无法启动(看起来没有理由)。结果发现是新版本的Skype占用了这个默认端口!我不得不去掉它的设置“将80和443端口作为入站连接的替代端口”。