Production Setup on Digital Ocean

Install Docker

  • Visit DigitalOcean and login.
  • Click the Create Droplet button.
  • Open the One-click apps tab.
  • Select Docker with your preferred version.
  • Continue creating the droplet as you normally would.
  • If needed, check your e-mail for the droplet root password.

SSH to your Server

Find the IP address of the droplet in the DigitalOcean interface. Use it to connect to the server.

  1. ssh root@ipaddress

You may be prompted for a password. Type the one you found within your e-mailbox. It’ll then ask you to change the password.

You can now check if Docker is available:

  1. $root@server:~# docker

Set Up Your Laravel Project

  1. $root@server:~# apt-get install git
  2. $root@server:~# git clone https://github.com/laravel/laravel
  3. $root@server:~# cd laravel
  4. $root@server:~/laravel/ git submodule add https://github.com/Laradock/laradock.git
  5. $root@server:~/laravel/ cd laradock

Install docker-compose command

  1. $root@server:~/laravel/laradock# curl -L https://github.com/docker/compose/releases/download/1.8.0/run.sh > /usr/local/bin/docker-compose
  2. $root@server:~/chmod +x /usr/local/bin/docker-compose

Enter the laradock folder and rename env-example to .env.

  1. $root@server:~/laravel/laradock# cp env-example .env

Create Your Laradock Containers

  1. $root@server:~/laravel/laradock# docker-compose up -d nginx mysql

Note that more containers are available, find them in the docs or the docker-compose.yml file.

Go to Your Workspace

  1. docker-compose exec workspace bash

Install and configure Laravel

Let’s install Laravel’s dependencies, add the .env file, generate the key and give proper permissions to the cache folder.

  1. $ root@workspace:/var/www# composer install
  2. $ root@workspace:/var/www# cp .env.example .env
  3. $ root@workspace:/var/www# php artisan key:generate
  4. $ root@workspace:/var/www# exit
  5. $root@server:~/laravel/laradock# cd ..
  6. $root@server:~/laravel# sudo chmod -R 777 storage bootstrap/cache

You can then view your Laravel site by visiting the IP address of your server in your browser. For example:

  1. http://192.168.1.1

It should show you the Laravel default welcome page.

However, we want it to show up using your custom domain name, as well.

Using Your Own Domain Name

Login to your DNS provider, such as Godaddy, Namecheap.

Point the Custom Domain Name Server to:

  1. ns1.digitalocean.com
  2. ns2.digitalocean.com
  3. ns3.digitalocean.com

Within DigitalOcean, you’ll need to change some settings, too.

Visit: https://cloud.digitalocean.com/networking/domains

Add your domain name and choose the server IP you’d provision earlier.

Serving Site With NGINX (HTTP ONLY)

Go back to command line.

  1. $root@server:~/laravel/laradock# cd nginx
  2. $root@server:~/laravel/laradock/nginx# vim laravel.conf

Remove default_server

  1. listen 80 default_server;
  2. listen [::]:80 default_server ipv6only=on;

And add server_name (your custom domain)

  1. listen 80;
  2. listen [::]:80 ipv6only=on;
  3. server_name yourdomain.com;

Rebuild Your Nginx

  1. $root@server:~/laravel/laradock# docker-compose down
  2. $root@server:~/laravel/laradock# docker-compose build nginx

Re Run Your Containers MYSQL and NGINX

  1. $root@server:~/laravel/laradock/nginx# docker-compose up -d nginx mysql

View Your Site with HTTP ONLY (http://yourdomain.com)

Run Site on SSL with Let’s Encrypt Certificate

Note: You need to Use Caddy here Instead of Nginx

To go Caddy Folders and Edit CaddyFile

  1. $root@server:~/laravel/laradock# cd caddy
  2. $root@server:~/laravel/laradock/caddy# vim Caddyfile

Remove 0.0.0.0:80

  1. 0.0.0.0:80
  2. root /var/www/public

and replace with your https://yourdomain.com

  1. https://yourdomain.com
  2. root /var/www/public

uncomment tls

  1. #tls self-signed

and replace self-signed with your email address

  1. tls serverbreaker@gmai.com

This is needed Prior to Creating Let’s Encypt

Run Your Caddy Container without the -d flag and Generate SSL with Let’s Encrypt

  1. $root@server:~/laravel/laradock/caddy# docker-compose up caddy

You’ll be prompt here to enter your email… you may enter it or not

  1. Attaching to laradock_mysql_1, laradock_caddy_1
  2. caddy_1 | Activating privacy features...
  3. caddy_1 | Your sites will be served over HTTPS automatically using Let's Encrypt.
  4. caddy_1 | By continuing, you agree to the Let's Encrypt Subscriber Agreement at:
  5. caddy_1 | https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf
  6. caddy_1 | Activating privacy features... done.
  7. caddy_1 | https://yourdomain.com
  8. caddy_1 | http://yourdomain.com

After it finishes, press Ctrl + C to exit.

Stop All Containers and ReRun Caddy and Other Containers on Background

  1. $root@server:~/laravel/laradock/caddy# docker-compose down
  2. $root@server:~/laravel/laradock/caddy# docker-compose up -d mysql caddy

View your Site in the Browser Securely Using HTTPS (https://yourdomain.com)

Note that Certificate will be Automatically Renew By Caddy

References:






PHPStorm XDebug设置

Intro

Wiring up Laravel, Laradock [Laravel+Docker] and PHPStorm to play nice together complete with remote xdebug’ing as icing on top! Although this guide is based on PHPStorm Windows, you should be able to adjust accordingly. This guide was written based on Docker for Windows Native.

Installation

  • This guide assumes the following:
    • you have already installed and are familiar with Laravel, Laradock and PHPStorm.
    • you have installed Laravel as a parent of laradock. This guide assumes /c/_dk/laravel.

hosts

  • Add laravel to your hosts file located on Windows 10 at C:\Windows\System32\drivers\etc\hosts. It should be set to the IP of your running container. Mine is: 10.0.75.2 On Windows you can find it by opening Windows Hyper-V Manager.

    • Windows Hyper-V Manager
  • Hosts File Editor makes it easy to change your hosts file.

    • Set laravel to your docker host IP. See Example.

Firewall

Your PHPStorm will need to be able to receive a connection from PHP xdebug either your running workspace or php-fpm containers on port 9000. This means that your Windows Firewall should either enable connections from the Application PHPStorm OR the port.

  • It is important to note that if the Application PHPStorm is NOT enabled in the firewall, you will not be able to recreate a rule to override that.
  • Also be aware that if you are installing/upgrade different versions of PHPStorm, you MAY have orphaned references to PHPStorm in your Firewall! You may decide to remove orphaned references however in either case, make sure that they are set to receive public TCP traffic.

Edit laradock/docker-compose.yml

Set the following variables:

  1. ### Workspace Utilities Container ###############
  2. workspace:
  3. build:
  4. context: ./workspace
  5. args:
  6. - INSTALL_XDEBUG=true
  7. - INSTALL_WORKSPACE_SSH=true
  8. ...
  9. ### PHP-FPM Container #####################
  10. php-fpm:
  11. build:
  12. context: ./php-fpm
  13. args:
  14. - INSTALL_XDEBUG=true
  15. ...

Edit xdebug.ini files

  • laradock/workspace/xdebug.ini
  • laradock/php-fpm/xdebug.ini

Set the following variables:

  1. xdebug.remote_autostart=1
  2. xdebug.remote_enable=1
  3. xdebug.remote_connect_back=1
  4. xdebug.cli_color=1

Need to clean house first?

Make sure you are starting with a clean state. For example, do you have other Laradock containers and images? Here are a few things I use to clean things up.

docker ps -a | awk '{ print $1,$2 }' | grep laradock_ | awk '{print $1}' | xargs -I {} docker rm {}

  • Delete all images containing laradock.

docker images | awk '{print $1,$2,$3}' | grep laradock_ | awk '{print $3}' | xargs -I {} docker rmi {} Note: This will only delete images that were built with Laradock, NOT laradock/* which are pulled down by Laradock such as laradock/workspace, etc. Note: Some may fail with: Error response from daemon: conflict: unable to delete 3f38eaed93df (cannot be forced) - image has dependent child images

  • I added this to my .bashrc to remove orphaned images.
  1. dclean() {
  2. processes=`docker ps -q -f status=exited`
  3. if [ -n "$processes" ]; then
  4. docker rm $processes
  5. fi
  6. images=`docker images -q -f dangling=true`
  7. if [ -n "$images" ]; then
  8. docker rmi $images
  9. fi
  10. }
  • If you frequently switch configurations for Laradock, you may find that adding the following and added to your .bashrc or equivalent useful:
  1. # remove laravel* containers
  2. # remove laravel_* images
  3. dcleanlaradockfunction()
  4. {
  5. echo 'Removing ALL containers associated with laradock'
  6. docker ps -a | awk '{ print $1,$2 }' | grep laradock | awk '{print $1}' | xargs -I {} docker rm {}
  7. # remove ALL images associated with laradock_
  8. # does NOT delete laradock/* which are hub images
  9. echo 'Removing ALL images associated with laradock_'
  10. docker images | awk '{print $1,$2,$3}' | grep laradock_ | awk '{print $3}' | xargs -I {} docker rmi {}
  11. echo 'Listing all laradock docker hub images...'
  12. docker images | grep laradock
  13. echo 'dcleanlaradock completed'
  14. }
  15. # associate the above function with an alias
  16. # so can recall/lookup by typing 'alias'
  17. alias dcleanlaradock=dcleanlaradockfunction

Let’s get a dial-tone with Laravel

  1. # barebones at this point
  2. docker-compose up -d nginx mysql
  3. # run
  4. docker-compose ps
  5. # Should see:
  6. Name Command State Ports
  7. -----------------------------------------------------------------------------------------------------------
  8. laradock_mysql_1 docker-entrypoint.sh mysqld Up 0.0.0.0:3306->3306/tcp
  9. laradock_nginx_1 nginx Up 0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp
  10. laradock_php-fpm_1 php-fpm Up 9000/tcp
  11. laradock_volumes_data_1 true Exit 0
  12. laradock_volumes_source_1 true Exit 0
  13. laradock_workspace_1 /sbin/my_init Up 0.0.0.0:2222->22/tcp

Enable xDebug on php-fpm

In a host terminal sitting in the laradock folder, run: .php-fpm/xdebug status You should see something like the following:

  1. xDebug status
  2. laradock_php-fpm_1
  3. PHP 7.0.9 (cli) (built: Aug 10 2016 19:45:48) ( NTS )
  4. Copyright (c) 1997-2016 The PHP Group
  5. Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
  6. with Xdebug v2.4.1, Copyright (c) 2002-2016, by Derick Rethans

Other commands include .php-fpm/xdebug start | stop.

If you have enabled xdebug=true in docker-compose.yml/php-fpm, xdebug will already be running when php-fpm is started and listening for debug info on port 9000.

PHPStorm Settings

  • Here are some settings that are known to work:

    • Settings/BuildDeploymentConnection

      • Settings/BuildDeploymentConnection
    • Settings/BuildDeploymentConnectionMappings

      • Settings/BuildDeploymentConnectionMappings
    • Settings/BuildDeploymentDebugger

      • Settings/BuildDeploymentDebugger
    • Settings/EditRunConfigurationRemoteWebDebug

      • Settings/EditRunConfigurationRemoteWebDebug
    • Settings/EditRunConfigurationRemoteExampleTestDebug

      • Settings/EditRunConfigurationRemoteExampleTestDebug
    • Settings/LangsPHPDebug

      • Settings/LangsPHPDebug
    • Settings/LangsPHPInterpreters

      • Settings/LangsPHPInterpreters
    • Settings/LangsPHPPHPUnit

      • Settings/LangsPHPPHPUnit
    • Settings/LangsPHPServers

      • Settings/LangsPHPServers
    • RemoteHost To switch on this view, go to: Menu/Tools/Deployment/Browse Remote Host.

      • RemoteHost
    • RemoteWebDebug

      • DebugRemoteOn
    • EditRunConfigurationRemoteWebDebug Go to: Menu/Run/Edit Configurations.

      • EditRunConfigurationRemoteWebDebug
    • EditRunConfigurationRemoteExampleTestDebug Go to: Menu/Run/Edit Configurations.

      • EditRunConfigurationRemoteExampleTestDebug
    • WindowsFirewallAllowedApps Go to: Control Panel\All Control Panel Items\Windows Firewall\Allowed apps.

      • WindowsFirewallAllowedApps.png
    • hosts Edit: C:\Windows\System32\drivers\etc\hosts.

Usage

Run ExampleTest

  • right-click on tests/ExampleTest.php
    • Select: Run 'ExampleTest.php' or Ctrl+Shift+F10.
    • Should pass!! You just ran a remote test via SSH!

Debug ExampleTest

  • Open to edit: tests/ExampleTest.php
  • Add a BreakPoint on line 16: $this->visit('/')
  • right-click on tests/ExampleTest.php
    • Select: Debug 'ExampleTest.php'.
    • Should have stopped at the BreakPoint!! You are now debugging locally against a remote Laravel project via SSH!
    • Remote Test Debugging Success

Debug WebSite

  • In case xDebug is disabled, from the laradock folder run: .php-fpm/xdebug start.

    • To switch xdebug off, run: .php-fpm/xdebug stop
  • Start Remote Debugging

    • DebugRemoteOn
  • Open to edit: bootstrap/app.php

  • Add a BreakPoint on line 14: $app = new Illuminate\Foundation\Application(
  • Reload Laravel Site
    • Should have stopped at the BreakPoint!! You are now debugging locally against a remote Laravel project via SSH!
    • Remote Debugging Success

Let’s shell into workspace

Assuming that you are in laradock folder, type: ssh -i workspace/insecure_id_rsa -p2222 root@laravel Cha Ching!!!!

  • workspace/insecure_id_rsa.ppk may become corrupted. In which case:
    • fire up puttygen
    • import workspace/insecure_id_rsa
    • save private key to workspace/insecure_id_rsa.ppk

KiTTY

Kitty KiTTY is a fork from version 0.67 of PuTTY.

  • Here are some settings that are working for me:
    • Session
    • Terminal
    • Window
    • WindowAppearance
    • Connection
    • ConnectionData
    • ConnectionSSH
    • ConnectionSSHAuth
    • TerminalShell






运行Laravel Dusk测试

Option 1: Without Selenium

Intro

This is a guide to run Dusk tests in your workspace container with headless google-chrome and chromedriver. It has been tested with Laravel 5.4 and 5.5.

Workspace Setup

Update your .env with following entries:

  1. ...
  2. # Install Laravel installer bin to setup demo app
  3. WORKSPACE_INSTALL_LARAVEL_INSTALLER=true
  4. ...
  5. # Install all the necessary dependencies for running Dusk tests
  6. WORKSPACE_INSTALL_DUSK_DEPS=true
  7. ...

Then run below to build your workspace.

  1. docker-compose build workspace

Application Setup

Run a workspace container and you will be inside the container at /var/www directory.

  1. docker-compose run workspace bash
  2. /var/www#> _

Create new Laravel application named dusk-test and install Laravel Dusk package.

  1. /var/www> laravel new dusk-test
  2. /var/www> cd dusk-test
  3. /var/www/dusk-test> composer require --dev laravel/dusk
  4. /var/www/dusk-test> php artisan dusk:install

Create .env.dusk.local by copying from .env file.

  1. /var/www/dusk-test> cp .env .env.dusk.local

Update the APP_URL entry in .env.dusk.local to local Laravel server.

  1. APP_URL=http://localhost:8000

You will need to run chromedriver with headless and no-sandbox flag. In Laravel Dusk 2.x it is already set headless so you just need to add no-sandbox flag. If you on previous version 1.x, you will need to update your DustTestCase#driver as shown below.

  1. <?php
  2. ...
  3. abstract class DuskTestCase extends BaseTestCase
  4. {
  5. ...
  6. /**
  7. * Update chrome driver with below flags
  8. */
  9. protected function driver()
  10. {
  11. $options = (new ChromeOptions)->addArguments([
  12. '--disable-gpu',
  13. '--headless',
  14. '--no-sandbox'
  15. ]);
  16. return RemoteWebDriver::create(
  17. 'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
  18. ChromeOptions::CAPABILITY, $options
  19. )
  20. );
  21. }
  22. }

Choose Chrome Driver Version (Optional)

You could choose to use either:

  1. Chrome Driver shipped with Laravel Dusk. (Default)
  2. Chrome Driver installed in workspace container. (Required tweak on DuskTestCase class)

For Laravel 2.x, you need to update DuskTestCase#prepare method if you wish to go with option #2.

  1. <?php
  2. ...
  3. abstract class DuskTestCase extends BaseTestCase
  4. {
  5. ...
  6. public static function prepare()
  7. {
  8. // Only add this line if you wish to use chrome driver installed in workspace container.
  9. // You might want to read the file path from env file.
  10. static::useChromedriver('/usr/local/bin/chromedriver');
  11. static::startChromeDriver();
  12. }

For Laravel 1.x, you need to add DuskTestCase#buildChromeProcess method if you wish to go with option #2.

  1. <?php
  2. ...
  3. use Symfony\Component\Process\ProcessBuilder;
  4. abstract class DuskTestCase extends BaseTestCase
  5. {
  6. ...
  7. /**
  8. * Only add this method if you wish to use chrome driver installed in workspace container
  9. */
  10. protected static function buildChromeProcess()
  11. {
  12. return (new ProcessBuilder())
  13. ->setPrefix('chromedriver')
  14. ->getProcess()
  15. ->setEnv(static::chromeEnvironment());
  16. }
  17. ...
  18. }

Run Dusk Tests

Run local server in workspace container and run Dusk tests.

  1. # alias to run Laravel server in the background (php artisan serve --quiet &)
  2. /var/www/dusk-test> serve
  3. # alias to run Dusk tests (php artisan dusk)
  4. /var/www/dusk-test> dusk
  5. PHPUnit 6.4.0 by Sebastian Bergmann and contributors.
  6. . 1 / 1 (100%)
  7. Time: 837 ms, Memory: 6.00MB

Option 2: With Selenium

Intro

Setting up Laravel Dusk tests to run with Laradock appears be something that eludes most Laradock users. This guide is designed to show you how to wire them up to work together. This guide is written with macOS and Linux in mind. As such, it’s only been tested on macOS. Feel free to create pull requests to update the guide for Windows-specific instructions.

This guide assumes you know how to use a DNS forwarder such as dnsmasq or are comfortable with editing the /etc/hosts file for one-off DNS changes.

DNS Setup

According to RFC-2606, only four TLDs are reserved for local testing[^1]:

  • .test
  • .example
  • .invalid
  • .localhost

A common TLD used for local development is .dev, but newer versions of Google Chrome (such as the one bundled with the Selenium Docker image), will fail to resolve that DNS as there will appear to be a name collision.

The recommended extension is .test for your Laravel web apps because you’re running tests. Using a DNS forwarder such as dnsmasq or by editing the /etc/hosts file, configure the host to point to localhost.

For example, in your /etc/hosts file:

  1. ##
  2. # Host Database
  3. #
  4. # localhost is used to configure the loopback interface
  5. # when the system is booting. Do not change this entry.
  6. ##
  7. 127.0.0.1 localhost
  8. 255.255.255.255 broadcasthost
  9. ::1 localhost
  10. 127.0.0.1 myapp.test

This will ensure that when navigating to myapp.test, it will route the request to 127.0.0.1 which will be handled by Nginx in Laradock.

Docker Compose setup

In order to make the Selenium container talk to the Nginx container appropriately, the docker-compose.yml needs to be edited to accommodate this. Make the following changes:

  1. ...
  2. selenium:
  3. ...
  4. depends_on:
  5. - nginx
  6. links:
  7. - nginx:<your_domain>

This allows network communication between the Nginx and Selenium containers and it also ensures that when starting the Selenium container, the Nginx container starts up first unless it’s already running. This allows the Selenium container to make requests to the Nginx container, which is necessary for running Dusk tests. These changes also link the nginx environment variable to the domain you wired up in your hosts file.

Laravel Dusk Setup

In order to make Laravel Dusk make the proper request to the Selenium container, you have to edit the DuskTestCase.php file that’s provided on the initial installation of Laravel Dusk. The change you have to make deals with the URL the Remote Web Driver attempts to use to set up the Selenium session.

One recommendation for this is to add a separate config option in your .env.dusk.local so it’s still possible to run your Dusk tests locally should you want to.

.env.dusk.local

  1. ...
  2. USE_SELENIUM=true

DuskTestCase.php

  1. abstract class DuskTestCase extends BaseTestCase
  2. {
  3. ...
  4. protected function driver()
  5. {
  6. if (env('USE_SELENIUM', 'false') == 'true') {
  7. return RemoteWebDriver::create(
  8. 'http://selenium:4444/wd/hub', DesiredCapabilities::chrome()
  9. );
  10. } else {
  11. return RemoteWebDriver::create(
  12. 'http://localhost:9515', DesiredCapabilities::chrome()
  13. );
  14. }
  15. }
  16. }

Running Laravel Dusk Tests

Now that you have everything set up, to run your Dusk tests, you have to SSH into the workspace container as you normally would: docker-compose exec --user=laradock workspace bash

Once inside, you can change directory to your application and run:

php artisan dusk

One way to make this easier from your project is to create a helper script. Here’s one such example:

  1. #!/usr/bin/env sh
  2. LARADOCK_HOME="path/to/laradock"
  3. pushd ${LARADOCK_HOME}
  4. docker-compose exec --user=laradock workspace bash -c "cd my-project && php artisan dusk && exit"

This invokes the Dusk command from inside the workspace container but when the script completes execution, it returns your session to your project directory.

[^1]: Don’t Use .dev for Development