Настройка окружения для web-разработки на Mac OS X
Установку необходимого софта будем производить с использованием менеджера недостающих пакетов для macOS — Homebrew. Если он у вас еще не устанолен, сперва ставим Xcode через AppStore либо в терминале набираем команду:
согласившись с лицензионным соглашением.
Установка Homebrew
Открываем терминал (вместо стандартного я использую ITerm2) и запускаем установку командой:
После установки обновляемся, проверяем все ли в порядке:
В качестве сервера баз данных я решил использовать MariaDB.
Cтавим MariaDB:
Выпоним первоначальную настройку сервера:
и проверяем подключение:
Займемся web сервером nginx:
Настройка nginx и создание структуры директорий.
Для виртуальных хостов я использую следующую структуру (вы можете использовать другую, удобную вам но не забудьте исправить пути в конфигах!):
Конфигурационные файлы вирутальных хостов.
Я использую следующую схему:
После установки nginx, в директории /usr/local/etc/nginx/ имеется стандартный конфигурационный файл nginx.conf. Приведем его к следуюущему виду:
Далее пишем конфигурацию виртуального хоста в директории /usr/local/etc/nginx/sites-available/
Создаем символьную ссылку:
Установка PHP
Если используете zsh то:
либо (в зависимости от того какой используется шел)
Версии должны быть одинаковыми!
Далее создадим файл index.php для проверки:
В адресной строке браузера набираем localhost и смотрим результат. Чтобы сервисы автоматически запускались после перезагрузки:
Вот вроде бы и все. Если возникнут вопросы, пишите в комментариях либо через форму обратной связи на странице контактов.
Установка nginx php-fpm mysql mac os x mavericks
Устнановка Homebrew
Настраиваем терминал
Установка PHP 5.5 и PHP-FPM
Установка MySQL сервера
Установка Nginx
Добавляем алиасы для удобноого запуска
Комментарии
А на Yosemite пробовали поставить?
Да конечно, сам сейчас пользуюсь Yosemite — всё работает отлично.
Подскажите, при установке на Yosemite, после установке nginx делаю curl -IL http://localhost:8080, получаю
curl: (7) Failed to connect to localhost port 8080: Connection refused.
Так же после установки пхп56, делаю lsof -Pni4 | grep LISTEN | grep php, получаю тишину.
Ну так если Apache небыл запущен, nginx должен быть доступен на 80 порту.
Покопай в сторону php-fpm. Вот похожая проблема http://serverfault.com/questions/617789/nginx-error-stating-connection-refused-to-php-fpm-port
Для начала удали из конфига всё что связано с php-fpm, положи в корень сайта html файлик и посмотри, будет ли nginx работать со статикой. Если всё хорошо, значит пробуй дальше настраивать php-fpm
Спасибо, разобрался. Проблема была действительно в php-fpm:)
Сделайте rss, чтобы следить за новостям.
Рад, что мои заметки пригодились. Обязательно подумаю насчёт rss, спасибо.
How to setup Nginx and PHP7.1 with FPM on Mac OS X without crying
I had problems with my nginx for months. I read a ton of articles online but couldn’t find a solution. Most of what I saw was for php7.0 , and they used php-fpm-sock file which clearly does not exist in php7.1 . Creating and configuring php7.1 to use the sock file was a different kettle of fish on it’s own. I failed at it several times. When I upgraded to High Sierra (which basically wiped my system clean due to multiple failures), I had to start setup all over again. I decided to take my time and actually tackle this nginx setup issue. There was still no tutorial on it that worked for me. I made up my mind to figure it out on my own. Did I? This article will explain how I did it.
If you are new to http servers on your local machine, this article would make setting up nginx pretty easy for you even if you don’t understand most of the stuff. If you use LAMP or WAMP or any of that, you might want to go read up on setting up nginx for your OS before coming right here. The nginx configurations would be the same. Just the folders to find the nginx.config file for nginx may change from OS to OS. Yes, this should work for non Mac users as well.
To make this article pretty useful to you, I’d skip a lot of stuff that are not the focus (stuff that there are probably like 1,000 articles on already). I’d speed through a lot of this. I use High Sierra on my Mac (I used Sierra before) so I cannot guarantee what would happen for other versions of macOS X. If you are following and anything is missing, do not fret. Just Google how to install it and then continue with this setup.
If you already have Nginx and PHP7.1 installed, you can skip to the installation section and head straight to configuration.
INSTALLATION
We are going to use Homebrew for all our installations. It makes life easy and it is pretty straightforward. Click here to read about it or just install right away.
When you are done, ensure homebrew’s environment is setup correctly.
Next we’re going to install a launchctl wrapper that will stop, start, and restart any service we install with brew.
Let’s install php7.1 with fpm and display the version after installation.
Start PHP right away.
We would not have to setup much for PHP7.1 with FPM because it comes pretty configured right out of the box. Let’s just get nginx and get the party going.
We are done with installations for now, time for configurations. Nginx should be running on port 8080 if you also have apache installed and running. Either way, you should see which port it is running on after installation, so you can quickly visit http://localhost:8080 to see the default nginx homepage (use the port displayed in your terminal after setup instead, if it is not 8080).
THE CONFIGURATION
When installed with homebrew, Nginx’s configuration file would be found in /usr/local/etc/nginx . Open it with any editor you like (I use nano to save time).
We are going to leave everything the way it is and just edit only a few sections. The nginx.config file would be configured properly upon installation to serve static files. All your websites would be in /usr/local/var/www folder so that nginx can see them. Nginx mirrors all the files there to it’s html folder that can be found in /usr/local/Cellar/nginx/[version_number]/html as of this writing. If you want to set a different part for your files, edit this block of the config file and set a different root .
Don’t forget to add index.php to the index list so that nginx can automatically load that file when it serves your site.
The next thing is to setup how our php files are proxied for execution. Edit your block to match the following.
I left the fastcgi_param line commented out just incase you need to set something there later. All params are already included below it and the fastcgi.conf file should have all the settings required to use php-fpm . Save your file and restart nginx.
If you are using multiple configuration files (all stored in /sites-available ), you would have to adjust them one by one as well. You can store this setup block above in a separate file and include it in all of them if they all use the same root folder.
Time to test our beautiful setup. Create an info.php file in /usr/local/var/www folder and put any php code of your choice that should output stuff (I echoed phpinfo() ). Go to http://localhost:8080/info.php and it should display just fine (use the port displayed in your terminal after setup if it is not 8080).
Now buddy, go enjoy your nginx and cry no more.
NGINX is a free, open-source, high-performance HTTP server known for its high performance, stability, rich feature set, simple configuration, and low resource consumption. If you want to see how nginx performs in handling requests and heavy usage when compared to apache, read Web server performance comparison. If you would like to understand better about the individual strengths of nginx and apache, checkout this article on Digital Ocean.
Настройка nginx + php72-fpm на macOS
Подобную настройку проводил на Ubuntu 16 и 18 без особых проблем, но с macOS на локальной машине не могу разобраться, мне кажется я не до конца понимаю основного принципа связи nginx c php-fpm. Я успешно настроил nginx, скачав его с менеджера пакетов brew. Через sudo nginx -v я получаю
Как обычно настроил несколько сайтов через sites-available и сделать include в nginx.conf. На этом этапе все хорошо, через
и т.д. я получаю результат.
PHP 7.2.9 (fpm-fcgi) (built: Aug 22 2018 02:58:58)
При запуске php7.2-fpm на linux через sudo service php7.2-fpm start создается сокет в /var/run/php/php7.2-fpm.sock И в файле /etc/php/7.2/fpm/pool.d/www.conf достаточно указать
Проделывая тоже самое на Mac, но немного в другой дирректории (структура php-fpm на Mac другая, но сути менять не должно) в /usr/local/etc/php/7.2/php-fpm.d/www.conf указывая тоже самые настройки (кроме Listen = /var/run/php/php7.2-fpm.sock я устанавливаю Listen = /usr/localvar/run/php/php7.2-fpm.sock ) при запуске sudo php-fpm я получаю ошибку
[25-Aug-2018 11:18:21] ERROR: [pool www] cannot get gid for group ‘www-data’: Undefined error: 0 (0) [25-Aug-2018 11:18:21] ERROR: FPM initialization failed
Я пробовал менять настройки, указывая вместо www-data имя моего локального профиля, но это дает такую же ошибку
[25-Aug-2018 11:18:21] ERROR: [pool www] cannot get gid for group ‘igortulkin’: Undefined error: 0 (0) [25-Aug-2018 11:18:21] ERROR: FPM initialization failed
Подскажите, что я делаю не так и как правильно связать php-fpm на Mac c Nginx?