Я новичок в linux / ubuntu, но хочу настроить веб-сервер apache на виртуальной машине ubuntu. Я создал виртуальную машину на Amazon AWS, установил apache. Но сейчас не могу достучаться до него через браузер. Я не уверен, правильно ли работает сервер apache или заблокированы ли какие-либо порты.
Проверял версию apache. Кажется, установлен с помощью "apache -version", и он показывает мне действующую версию и дату установки.
Проверяю открытые порты. Кажется, apache прослушивает некоторые порты (3609, 3614, 3615), но не порт 80? Может быть, в этом проблема? Как это исправить?
Изменить 1: На самом деле я хотел добавить несколько скриншотов, но я не могу этого сделать с репутацией ниже десяти.
Изменить 2:
Изменить 3: Localhost доступен с сервера. Значит, это проблема с брандмауэром / подключением. Но вот что странно: я могу пинговать порт 80 на ip сервера через telnet извне.
Изменить 4: Я могу подключиться к своему веб-серверу с другой виртуальной машины Amazon! Так что это значит: это проблема с группами безопасности от Amazon? Я открываю много портов в моей группе безопасности для тестирования:
Apache2.conf выглядит так:
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
LockFile ${APACHE_LOCK_DIR}/accept.lock
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
##
## Server-Pool Size Regulation (MPM specific)
##
# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
# worker MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadLimit: ThreadsPerChild can be changed to this maximum value during a
# graceful restart. ThreadLimit can only be changed by stopping
# and starting Apache.
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
# It is also possible to omit any default MIME type and let the
# client's browser guess an appropriate action instead. Typically the
# browser will decide based on the file's extension then. In cases
# where no good assumption can be made, letting the default MIME type
# unset is suggested instead of forcing the browser to accept
# incorrect metadata.
#
DefaultType None
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
# Include module configuration:
Include mods-enabled/*.load
Include mods-enabled/*.conf
# Include list of ports to listen on and which to use for name based vhosts
Include ports.conf
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# Include of directories ignores editors' and dpkg's backup files,
# see the comments above for details.
# Include generic snippets of statements
Include conf.d/
# Include the virtual host configurations:
Include sites-enabled/
Файл ports.conf выглядит так:
NameVirtualHost *:80
Listen 80
<IfModule mod_ssl.c>
# If you add NameVirtualHost *:443 here, you will also have to change
# the VirtualHost statement in /etc/apache2/sites-available/default-ssl
# to <VirtualHost *:443>
# Server Name Indication for SSL named virtual hosts is currently not
# supported by MSIE on Windows XP.
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
Изменить 5:
Если я пытаюсь подключиться к веб-серверу, я получаю сообщение: «Веб-сайт недоступен:»
Изменить 6:
"etc / apache2 / sites-available / default" выглядит так:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
Изменить 7:
На самом деле я не могу пинговать свой хост, работает только telnet на 80-м порту.
Изменить 8:
результаты local telnet "localhost 80" и "netstat -l":
"телнет":
"netstat -l":
Изменить 9:
Поскольку кажется, что веб-сервер прослушивает IP-адрес ip6, я изменил свой "ports.conf" и добавил запись "Listen YOUR_AWS_IP: 80", как предложил "Christoph Eicke". Теперь веб-сервер, кажется, слушает адрес ip4. Но я все еще не могу подключиться к веб-серверу.
В тебе netstat -l
, я не вижу, чтобы на 80-м порту слушали IPv4. Однако ваш веб-сервер прослушивает интерфейс IPv6.
Имеет смысл, что вы можете подключиться к нему локально, потому что ваши инструменты, вероятно, уже могут говорить по IPv6, а localhost разрешает действующий IP-адрес IPv6 через /etc/hosts
. Но ваша сеть, вероятно, еще не поддерживает IPv6.
Возможно, у вас есть стандартный набор групп безопасности, а также один экземпляр EC2, но помните, что вы можете создать несколько групп безопасности и несколько экземпляров EC2, поэтому:
Вы должны назначить группу безопасности экземпляру EC2.
Перейдите на веб-сайт AWS -> EC2 -> Экземпляры -> выберите свой экземпляр -> кнопка Действия -> Сеть / Изменить группы безопасности -> здесь вы можете выполнить задание, в большинстве случаев просто установите флажок «по умолчанию» и сохраните.
Это не на 100% очевидно из вашего вопроса, поэтому могу я спросить, запустили ли вы Apache после его установки? «sudo /etc/init.d/apache2 status» сообщит вам, работает он на самом деле или нет.
Следующее место, которое я бы проверил, - это файл журнала Apache, который вы найдете в / var / log / apache2 /.
редактировать: Поскольку оба из них проверяются, вы можете видеть Apache локально с сервера? Запустите веб-браузер на сервере, укажите его на http://localhost
и посмотрим, что произойдет.
Редактировать 2: Если Apache запущен и правила брандмауэра отсутствуют, то пора посмотреть в самой конфигурации Apache на предмет директив, которые разрешают локальные подключения, но не удаленные. Различные файлы конфигурации должны быть в / etc / apache2; обратите внимание на такие строки, как «запретить от всех» или «разрешить от <диапазон адресов>».
У меня возникли проблемы с подключением к порту 8080. Я установил Apache2 sudo apt-get install Apache2
и смог прослушать порт 8080. Похоже, по умолчанию Apache2 не установлен на EC2.