Coder Social home page Coder Social logo

docker-compose-laravel's Introduction

docker-compose-laravel

A pretty simplified Docker Compose workflow that sets up a LEMP network of containers for local Laravel development. You can view the full article that inspired this repo here.

Usage

To get started, make sure you have Docker installed on your system, and then clone this repository.

Next, navigate in your terminal to the directory you cloned this, and spin up the containers for the web server by running docker-compose up -d --build app.

After that completes, follow the steps from the src/README.md file to get your Laravel project added in (or create a new blank one).

Note: Your MySQL database host name should be mysql, not localhost. The username and database should both be homestead with a password of secret.

Bringing up the Docker Compose network with app instead of just using up, ensures that only our site's containers are brought up at the start, instead of all of the command containers as well. The following are built for our web server, with their exposed ports detailed:

  • nginx - :80
  • mysql - :3306
  • php - :9000
  • redis - :6379
  • mailhog - :8025

Three additional containers are included that handle Composer, NPM, and Artisan commands without having to have these platforms installed on your local computer. Use the following command examples from your project root, modifying them to fit your particular use case.

  • docker-compose run --rm composer update
  • docker-compose run --rm npm run dev
  • docker-compose run --rm artisan migrate

Permissions Issues

If you encounter any issues with filesystem permissions while visiting your application or running a container command, try completing one of the sets of steps below.

If you are using your server or local environment as the root user:

  • Bring any container(s) down with docker-compose down
  • Replace any instance of php.dockerfile in the docker-compose.yml file with php.root.dockerfile
  • Re-build the containers by running docker-compose build --no-cache

If you are using your server or local environment as a user that is not root:

  • Bring any container(s) down with docker-compose down
  • In your terminal, run export UID=$(id -u) and then export GID=$(id -g)
  • If you see any errors about readonly variables from the above step, you can ignore them and continue
  • Re-build the containers by running docker-compose build --no-cache

Then, either bring back up your container network or re-run the command you were trying before, and see if that fixes it.

Persistent MySQL Storage

By default, whenever you bring down the Docker network, your MySQL data will be removed after the containers are destroyed. If you would like to have persistent data that remains after bringing containers down and back up, do the following:

  1. Create a mysql folder in the project root, alongside the nginx and src folders.
  2. Under the mysql service in your docker-compose.yml file, add the following lines:
volumes:
  - ./mysql:/var/lib/mysql

Usage in Production

While I originally created this template for local development, it's robust enough to be used in basic Laravel application deployments. The biggest recommendation would be to ensure that HTTPS is enabled by making additions to the nginx/default.conf file and utilizing something like Let's Encrypt to produce an SSL certificate.

Compiling Assets

This configuration should be able to compile assets with both laravel mix and vite. In order to get started, you first need to add --host 0.0.0.0 after the end of your relevant dev command in package.json. So for example, with a Laravel project using Vite, you should see:

"scripts": {
  "dev": "vite --host 0.0.0.0",
  "build": "vite build"
},

Then, run the following commands to install your dependencies and start the dev server:

  • docker-compose run --rm npm install
  • docker-compose run --rm --service-ports npm run dev

After that, you should be able to use @vite directives to enable hot-module reloading on your local Laravel application.

Want to build for production? Simply run docker-compose run --rm npm run build.

MailHog

The current version of Laravel (9 as of today) uses MailHog as the default application for testing email sending and general SMTP work during local development. Using the provided Docker Hub image, getting an instance set up and ready is simple and straight-forward. The service is included in the docker-compose.yml file, and spins up alongside the webserver and database services.

To see the dashboard and view any emails coming through the system, visit localhost:8025 after running docker-compose up -d site.

docker-compose-laravel's People

Contributors

aschmelyun avatar dcrystalj avatar djedaini-abdelhak avatar filipbekic01 avatar oranges13 avatar smusmu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docker-compose-laravel's Issues

Artisan Exiting with Code 255; Composer Artisan Discovery Memory Leak

I've been running this awesome setup you have here for about 4-5 months now and it has always worked without a hitch, but today randomly, with no changes to any of the setup you have here, artisan seems to just be not working at all, period.

It was working 100% fine yesterday when I was working the app, and I spun it down using the typical docker-compose down --remove-orphans --v like I've always done with this.

Today coming back and running docker-compose up -d --build like I always do to spin it up works just fine, but for some reason now when I run: docker-compose run --rm artisan migrate it just quits out with 255 exit code and no error message at all.

Here is what happens after running docker-compose --verbose run --rm artisan, for example, which had always shown me the artisan available commands before today:

...
Starting mysql ...
compose.parallel.feed_queue: Pending: {<Container: mysql (b7485f)>}
compose.parallel.feed_queue: Starting producer thread for <Container: mysql (b7485f)>
Starting mysql ... done
compose.parallel.feed_queue: Pending: set()
compose.parallel.parallel_execute_iter: Finished processing: <Service: mysql>
compose.parallel.feed_queue: Pending: set()
compose.cli.verbose_proxy.proxy_callable: docker inspect_network <- ('odysseus-api_laravel')
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/networks/odysseus-api_laravel HTTP/1.1" 200 1290
compose.cli.verbose_proxy.proxy_callable: docker inspect_network -> {'Attachable': True,
 'ConfigFrom': {'Network': ''},
 'ConfigOnly': False,
 'Containers': {'8fb9376af30d40eb75de066e6b71dfe411133f1d80cdb363ffb522fa5f65eb03': {'EndpointID': 'f3864f8c85956ce421af5399fb6f76dcad08b743a9f9fd38f17aef386217d85f',
                                                                                     'IPv4Address': '172.18.0.2/16',
                                                                                     'IPv6Address': '',
                                                                                     'MacAddress': '02:42:ac:12:00:02',
                                                                                     'Name': 'php'},
                'a0ed964f879ea0a1fa7193ee6e218b9e287fa983ceead5d1b2f7e20246b8ebc3': {'EndpointID': '7576f1a58432fc8a89abdf9b2caef47fe4c4068b1af7bc3db36a0208f793bf2d',
                                                                                     'IPv4Address': '172.18.0.5/16',
...
compose.cli.verbose_proxy.proxy_callable: docker inspect_network <- ('odysseus-api_default')
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/networks/odysseus-api_default HTTP/1.1" 200 561
compose.cli.verbose_proxy.proxy_callable: docker inspect_network -> {'Attachable': True,
 'ConfigFrom': {'Network': ''},
 'ConfigOnly': False,
 'Containers': {},
 'Created': '2020-08-30T18:33:29.7785226Z',
 'Driver': 'bridge',
 'EnableIPv6': False,
 'IPAM': {'Config': [{'Gateway': '172.19.0.1', 'Subnet': '172.19.0.0/16'}],
          'Driver': 'default',
          'Options': None},
...
compose.cli.verbose_proxy.proxy_callable: docker inspect_image <- ('odysseus-api_artisan')
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/images/odysseus-api_artisan/json HTTP/1.1" 200 None
compose.cli.verbose_proxy.proxy_callable: docker inspect_image -> {'Architecture': 'amd64',
 'Author': '',
 'Comment': '',
 'Config': {'ArgsEscaped': True,
            'AttachStderr': False,
            'AttachStdin': False,
            'AttachStdout': False,
            'Cmd': ['php-fpm'],
            'Domainname': '',
            'Entrypoint': ['docker-php-entrypoint'],
...
compose.cli.verbose_proxy.proxy_callable: docker containers <- (all=False, filters={'label': ['com.docker.compose.project=odysseus-api', 'com.docker.compose.service=artisan', 'com.docker.compose.oneoff=False']})
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/containers/json?limit=-1&all=0&size=0&trunc_cmd=0&filters=%7B%22label%22%3A+%5B%22com.docker.compose.project%3Dodysseus-api%22%2C+%22com.docker.compose.service%3Dartisan%22%2C+%22com.docker.compose.oneoff%3DFalse%22%5D%7D HTTP/1.1" 200 3
compose.cli.verbose_proxy.proxy_callable: docker containers -> (list with 0 items)
compose.cli.verbose_proxy.proxy_callable: docker containers <- (all=False, filters={'label': ['com.docker.compose.project=odysseusapi', 'com.docker.compose.service=artisan', 'com.docker.compose.oneoff=False']})
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/containers/json?limit=-1&all=0&size=0&trunc_cmd=0&filters=%7B%22label%22%3A+%5B%22com.docker.compose.project%3Dodysseusapi%22%2C+%22com.docker.compose.service%3Dartisan%22%2C+%22com.docker.compose.oneoff%3DFalse%22%5D%7D HTTP/1.1" 200 3
compose.cli.verbose_proxy.proxy_callable: docker containers -> (list with 0 items)
compose.cli.verbose_proxy.proxy_callable: docker create_host_config <- (links=[], port_bindings={}, binds=['/home/dfoster/Code/odysseus-api/src:/var/www/html:rw'], volumes_from=[], privileged=False, network_mode='odysseus-api_laravel', devices=None, dns=None, dns_opt=None, dns_search=None, restart_policy=None, runtime=None, cap_add=None, cap_drop=None, mem_limit=None, mem_reservation=None, memswap_limit=None, ulimits=None, log_config={'Type': '', 'Config': {}}, extra_hosts=None, read_only=None, pid_mode=None, security_opt=None, ipc_mode=None, cgroup_parent=None, cpu_quota=None, shm_size=None, sysctls=None, pids_limit=None, tmpfs=[], oom_kill_disable=None, oom_score_adj=None, mem_swappiness=None, group_add=None, userns_mode=None, init=None, init_path=None, isolation=None, cpu_count=None, cpu_percent=None, nano_cpus=None, volume_driver=None, cpuset_cpus=None, cpu_shares=None, storage_opt=None, blkio_weight=None, blkio_weight_device=None, device_read_bps=None, device_read_iops=None, device_write_bps=None, device_write_iops=None, mounts=None, device_cgroup_rules=None, cpu_period=None, cpu_rt_period=None, cpu_rt_runtime=None)
compose.cli.verbose_proxy.proxy_callable: docker create_host_config -> {'Binds': ['/home/dfoster/Code/odysseus-api/src:/var/www/html:rw'],
 'Links': [],
 'LogConfig': {'Config': {}, 'Type': ''},
 'NetworkMode': 'odysseus-api_laravel',
 'PortBindings': {},
 'VolumesFrom': []}
compose.cli.verbose_proxy.proxy_callable: docker create_container <- (entrypoint=['php', '/var/www/html/artisan'], volumes={'/var/www/html': {}}, working_dir='/var/www/html', command=None, tty=True, stdin_open=True, detach=False, ports=[], name='odysseus-api_artisan_run_2eaed7d9b219', environment=[], labels={'com.docker.compose.project': 'odysseus-api', 'com.docker.compose.service': 'artisan', 'com.docker.compose.oneoff': 'True', 'com.docker.compose.project.working_dir': '/home/dfoster/Code/odysseus-api', 'com.docker.compose.project.config_files': 'docker-compose.yml', 'com.docker.compose.slug': '2eaed7d9b2190bb0076e6ad931c9880eebf1904f90a0ceae39cfe0d8b2e1ae0', 'com.docker.compose.version': '1.26.2'}, image='odysseus-api_artisan', host_config={'NetworkMode': 'odysseus-api_laravel', 'VolumesFrom': [], 'Binds': ['/home/dfoster/Code/odysseus-api/src:/var/www/html:rw'], 'PortBindings': {}, 'Links': [], 'LogConfig': {'Type': '', 'Config': {}}}, networking_config={'EndpointsConfig': {'odysseus-api_laravel': {'Aliases': ['artisan'], 'IPAMConfig': {}}}})
urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/containers/create?name=odysseus-api_artisan_run_2eaed7d9b219 HTTP/1.1" 201 88
compose.cli.verbose_proxy.proxy_callable: docker create_container -> {'Id': '076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905',
 'Warnings': []}
compose.cli.verbose_proxy.proxy_callable: docker inspect_container <- ('076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905')
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/containers/076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905/json HTTP/1.1" 200 None
compose.cli.verbose_proxy.proxy_callable: docker inspect_container -> {'AppArmorProfile': '',
 'Args': ['/var/www/html/artisan'],
 'Config': {'AttachStderr': True,
            'AttachStdin': True,
            'AttachStdout': True,
            'Cmd': None,
            'Domainname': '',
            'Entrypoint': ['php', '/var/www/html/artisan'],
            'Env': ['PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
                    'PHPIZE_DEPS=autoconf \t\tdpkg-dev dpkg \t\tfile \t\t'
...
compose.cli.verbose_proxy.proxy_callable: docker disconnect_container_from_network <- ('076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905', 'odysseus-api_laravel')
urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/networks/odysseus-api_laravel/disconnect HTTP/1.1" 200 0
compose.cli.verbose_proxy.proxy_callable: docker disconnect_container_from_network -> None
compose.cli.verbose_proxy.proxy_callable: docker connect_container_to_network <- ('076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905', 'odysseus-api_laravel', aliases=[], ipv4_address=None, ipv6_address=None, links=[], link_local_ips=None)
urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/networks/odysseus-api_laravel/connect HTTP/1.1" 200 0
compose.cli.verbose_proxy.proxy_callable: docker connect_container_to_network -> None
compose.cli.main.call_docker: /usr/bin/docker start --attach --interactive 076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905
compose.cli.verbose_proxy.proxy_callable: docker remove_container <- ('076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905', force=True, v=True)
urllib3.connectionpool._make_request: http://localhost:None "DELETE /v1.25/containers/076569cb74c898181d5b4d3f790d69c767a05d6fff169a8dee6abdadb7847905?v=True&link=False&force=True HTTP/1.1" 204 0
compose.cli.verbose_proxy.proxy_callable: docker remove_container -> None

I'm currently running this through WSL 2 in Windows:

PS C:\Some\Path\To\User\dfost> wsl --list --v
  NAME                   STATE           VERSION
* Ubuntu-20.04           Running         2
  docker-desktop         Running         2
  docker-desktop-data    Running         2

Composer container seems to spin up and run its command JUST FINE however during the running of @php artisan package:discover --ansi via composer auto scripts ( package discovery) , the artisan line there just causes a MASSIVE memory leak which ends up eating up all my RAM in a matter of minutes.

I'm not sure if any of your stuff here causes this, but it's frustrating as this seems to have just kind of randomly started occurring with no changes to the config. Wondering if there is any chance for guidance/ideas?

Lmk if more information is needed.

UPDATE:

Also, this is what I get for just trying to spin that artisan container up in general:

docker-compose --verbose up artisan

Output:

Starting artisan ...
compose.parallel.feed_queue: Pending: {<Container: artisan (2005f8)>}
compose.parallel.feed_queue: Starting producer thread for <Container: artisan (2005f8)>
compose.cli.verbose_proxy.proxy_callable: docker attach <- ('2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017', stdout=True, stderr=True, stream=True)
urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/containers/2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017/attach?logs=0&stdout=1&stderr=1&stream=1 HTTP/1.1" 101 0
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/containers/2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017/json HTTP/1.1" 200 None
compose.cli.verbose_proxy.proxy_callable: docker attach -> <docker.types.daemon.CancellableStream object at 0x7f0d2c5868d0>
compose.cli.verbose_proxy.proxy_callable: docker start <- ('2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017')
compose.parallel.feed_queue: Pending: set()
compose.parallel.feed_queue: Pending: set()
urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/containers/2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017/start HTTP/1.1" 204 0
compose.cli.verbose_proxy.proxy_callable: docker start -> None
Starting artisan ... done
compose.parallel.feed_queue: Pending: set()
compose.parallel.parallel_execute_iter: Finished processing: <Service: artisan>
compose.parallel.feed_queue: Pending: set()
Attaching to artisan
compose.cli.verbose_proxy.proxy_callable: docker events <- (filters={'label': ['com.docker.compose.project=odysseus-api', 'com.docker.compose.oneoff=False']}, decode=True)
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/events?filters=%7B%22label%22%3A+%5B%22com.docker.compose.project%3Dodysseus-api%22%2C+%22com.docker.compose.oneoff%3DFalse%22%5D%7D HTTP/1.1" 200 None
compose.cli.verbose_proxy.proxy_callable: docker events -> <docker.types.daemon.CancellableStream object at 0x7f0d2c51a2d0>
compose.cli.verbose_proxy.proxy_callable: docker inspect_container <- ('2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017')
compose.cli.verbose_proxy.proxy_callable: docker wait <- ('2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017')
urllib3.connectionpool._make_request: http://localhost:None "GET /v1.25/containers/2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017/json HTTP/1.1" 200 None
urllib3.connectionpool._make_request: http://localhost:None "POST /v1.25/containers/2005f8039c97b7e855c22dc9df2f333af94c110c2e1548dfafd0a4d8cf2ef017/wait HTTP/1.1" 200 32
compose.cli.verbose_proxy.proxy_callable: docker inspect_container -> {'AppArmorProfile': '',
 'Args': ['/var/www/html/artisan'],
 'Config': {'AttachStderr': False,
            'AttachStdin': False,
            'AttachStdout': False,
            'Cmd': None,
            'Domainname': '',
            'Entrypoint': ['php', '/var/www/html/artisan'],
            'Env': ['PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
                    'PHPIZE_DEPS=autoconf \t\tdpkg-dev dpkg \t\tfile \t\t'
...
compose.cli.verbose_proxy.proxy_callable: docker wait -> {'Error': None, 'StatusCode': 255}
artisan exited with code 255

Watch for changes in the laravel project

Sorry if is a dumb question.

Is there a way to watch for changes and according update the project public files?

An equivalent of npm run watch so to speak.

So like docker-compose run --rm npm run watch.

Is there a way to archive this result? Thanks

localhost is currently unable to handle this request.

I got error in browser on docker up

This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500

I am on linux mint 19, docker and docker-compose are both of latest version.
Please, help to figure this out.

Persisting MySQL: Permission Error

Ubuntu 18.04

  mysql:
    image: mysql:5.7.29
    container_name: mysql
    restart: unless-stopped
    tty: true
    ports:
      - "3306:3306"
    volumes:
      - ./docker/mysql:/var/lib/mysql
    environment:
      MYSQL_DATABASE: homestead
      MYSQL_USER: homestead
      MYSQL_PASSWORD: secret
      MYSQL_ROOT_PASSWORD: secret
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    networks:
      - laravel

PermissionError: [Errno 13] Permission denied: '/home/laravel/playground/docker/mysql/ca-key.pem'

Steps to reproduce:

  • Add volume to mysql
  • Set all up
  • docker-compose down
  • docker-compose up -d

Add support for Storybook

Hi,
I've added the below to the docker compose file in case you are using Storybook with Laravel/Vue.

  storybook:
    image: node:13.7
    container_name: storybook
    volumes:
      - ./src:/var/www/html
    working_dir: /var/www/html
    command: npm run storybook
    ports:
      - "8082:3002"
    networks:
      - laravel

Regards
Bilal

Project directory "/var/www/html/." is not empty.

laravel

After running "sudo docker-compose run --rm composer create-project laravel/laravel ." Below is the error that I got.
[InvalidArgumentException]
Project directory "/var/www/html/." is not empty.

Very long TTFB times

I loaded the Docker setup, installed Statamic 3 and I'm seeing 7-10 second time to first byte delays.

Screenshot_1

Anyone else experiencing this?

Welcome to nginx

Hi there,

On my local, everything seemed that ok.
But I try to connect localhost:8080, it let me "wel come to ngninx" page. not laravel.

And when I try to deploy for elasticbeanstalk, it gives error.

Whats wrong with it?

mysql reject connection when i add volume to mysql in docker-compose.yml

Hi, I have a problem, I added volumes to mysql so that my data would not disappear by running the command "docker-compose down", I added:

volumes: 
-./mysql:/var/lib/mysql 

to the mysql configuration in the file docker-compose.yml along with the mysql directory at the root of the project, it doesn't give me errors when giving "docker-compose up" but when I try to do anything to the database, it rejects the connection with error 2002, even if I try to enter with heidi to the host and port rejects the connection, what can it be?

artisan tinker

Hi, When using the command docker-compose run --rm artisan tinker

I get the error

Writing to /.config/psysh is not allowed.

` at vendor/psy/psysh/src/ConfigPaths.php:217

213|             @\mkdir($dir, 0700, true);
214|         }
215| 
216|         if (!\is_dir($dir) || !\is_writable($dir)) {
217|             \trigger_error(\sprintf('Writing to %s is not allowed.', $dir), E_USER_NOTICE);
218| 
219|             return false;
220|         }`

I have added

user: 1000:1000 to php, composer and artisan.

Any suggestions would be appreciated

Too many containers

I see that on Github you created container for each tool such as npm, composer etc. What do you thinking about creating single container with all those tools in? For example, you can easly merge php and composer containers. What's better solution tho?

404 Not Found

Hi, go through all the steps but when I want to see the localhost:8080 I get nginx 404 error

Operation Not Permitted Nginx

Hello, I'm new to docker. I can't run the nginx container because of the volume mounting.
Here is the log.
(Laravel is in the src folder, no ports blocking)

/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration

/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/

/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh

10-listen-on-ipv6-by-default.sh: error: can not modify /etc/nginx/conf.d/default.conf (read-only file system?)

/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh

/docker-entrypoint.sh: Configuration complete; ready for start up

2020/07/11 20:53:25 [emerg] 1#1: open() "/etc/nginx/conf.d/default.conf" failed (1: Operation not permitted) in /etc/nginx/nginx.conf:31

nginx: [emerg] open() "/etc/nginx/conf.d/default.conf" failed (1: Operation not permitted) in /etc/nginx/nginx.conf:31

I have tried to build the nginx container with a seperate dockerfile to COPY the ./nginx/default.conf to /etc/nginx/conf.d but I only got the default Nginx welcome page.

Thank you for your help!

What's the point of the npm entrypoint?

Why is the npm container has an entrypoint of npm set?

If I understand correctly, the default behaviour of docker-compose run is to use the service's name as entrypoint? Why put it for this container then?

npm install doesn't work on my docker instance

I am having issue with following commands.
docker-compose run --rm npm install
docker-compose run --rm npm run dev

For some reason it never finish installation. I tried to change npm to latest & 14.0 both failed
I am running docker on windows. Everything else works fine. Can someone help me with this so I can compile my assets in laravel application.
PS: posting issue after hours of trial & errors, removing folder etc etc.

Run migration was failed

Hello,

This project looks pretty cool and helpful to me.

So, I'm trying to setup the Laravel project by using your Docker Compose. Everything looks fine the database was created but when I run the migration command. It's occurred an error in below.

.env configs:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Then run command:

docker-compose run --rm artisan migrate

Here is the error:

Starting docker-compose-laravel_mysql_1 ... done

   Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = homestead and table_name = migrations and table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:670
    666|         // If an exception occurs when attempting to run a query, we'll format the error
    667|         // message to include the bindings with SQL, which will make this exception a
    668|         // lot more helpful to the developer instead of just the database's errors.
    669|         catch (Exception $e) {
  > 670|             throw new QueryException(
    671|                 $query, $this->prepareBindings($bindings), $e
    672|             );
    673|         }
    674| 

  • Database name seems incorrect: You're using the default database name `homestead`. This database does not exist.
    
    Edit the `.env` file and use the correct database name in the `DB_DATABASE` key. 
    https://laravel.com/docs/master/database#configuration

Could you help to solve this issue please?

Best regards,

Natthawut

Permission problems in general

When you run sudo docker-compose run artisan vendor:publish ... and you publish some configuration file for example, it will create files as root and after edit i can't save it through my IDE since it's not created as me (linux user).

My idea is to re-run some kind of chown and chmod combination script after each container operation but it does not seem like a way to go. Any suggestions?

Docker compose up failed when building artisan

Docker compose up failed when building artisan

docker-compose up -d --build

ERROR: for artisan  Cannot start service artisan: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/var/www/html/artisan\": permission denied": unknown

App is right at /src folder.

Docker create files as root

If run command: docker-compose run --rm artisan make:model {modelName}
a file with root privileges is created
image
how to fix it?

Question regarding networks: laravel and default

Newbie here.

AFTER executing: andrew-beta(master) $ docker-compose up --build --detach site

I noticed that there were 2 networks associated with this project...laravel and default. I am not sure if this was done for a reason?

andrew-beta(master) $ docker network ls
NETWORK ID          NAME                  DRIVER              SCOPE
d0e11de5ac50        andrew-beta_default   bridge              local
639301a86522        andrew-beta_laravel   bridge              local
28eda924b827        bridge                bridge              local
3e067bc7e3c5        host                  host                local
6b8364dbf466        none                  null                local

If I add the laravel network to the npm service, as the other 5 services have, then the result is that these 6 services are all on the laravel network. Any reason to not to do this?

  npm:
    image: node:13.7
    container_name: npm
    volumes:
      - ./src:/var/www/html
    working_dir: /var/www/html
    entrypoint: ['npm']
    networks:
      - laravel

Thanks

Mike

Tried to add ssh container but of course couldn't reach to php

I tried to add an ssh container to the whole file to be able to connect to it using ssh command itself(I need this for a tool I'm using).
So, I added this service but couldn't map the php command here to run inside it.
I'll keep trying though to do this and update if I have something working.

  connector:
    image: abobija/ssh
    container_name: connector
    depends_on:
      - php
    ports:
      - "2222:22"
    restart: unless-stopped
    volumes:
      - ./src:/var/www/html
    working_dir: /var/www/html
    tty: true
    networks:
      - laravel

mySQL Database

One thing to note you should add in the Readme is the IP Address of the mySQL database needs to be the local network ip other wise the database will not connect. I tried with 127.0.0.1 and localhost didn't work

Cannot start service artisan no such file or directory

ERROR: for artisan  Cannot start service artisan: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"/var/www/html/artisan\": stat /var/www/html/artisan: no such file or directory": unknown
ERROR: Encountered errors while bringing up the project.

I'm running windows 10. I've verified that the artisan file is present in the src directory.

create laravel app inside scr

Hi is there a way to create a Laravel project inside of the src folder rather than moving one to it, I have tried too by using composer create-project --prefer-dist laravel/laravel src but this creates it in src/sr

thanks.

npm errors

First of all i would lie to thank you for such a great work you are doing for the community, words cannot admire that.
I am facing a issue when i run command docker-compose run --rm npm run dev
can someone guide me whats wrong?
npm-error

Yarn support

Since most of people use Yarn for JS dependencies, you should have container for that too :)

Can not find artisan file when starting artisan service.

Hi, so i'm following your instructions with an existing Laravel project. Everything goes fine until the "Creating artisan" step, after running docker-compose up -d --build. The error message is as follows:

ERROR: for artisan Cannot start service artisan: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: "/var/www/html/artisan": stat /var/www/html/artisan: no such file or directory": unknown
ERROR: Encountered errors while bringing up the project.

I'm very new to docker, I followed your instructions but added phpmyadmin and changed MySQL to MariaDB. Both docker and powershell are running as admin, and i'm sure the artisan file is actually there. I'm running the powershell prompt from the root folder, where the artisan file is located.

Do you have any idea what could be causing this?

Permission problems on Linux

I tried running this on Linux, but the Laravel welcome page won't load and a permission exception is thrown unless I do

sudo chmod 777 -R storage/
sudo chmod 777 -R bootstrap/cache/

...which I'm not sure if it's the safest option.

This seems to happen because "unlike on Mac or Windows, Docker on Linux has no layer of virtualization. As a result of this (and how containers work in general), operations run within the Docker container on shared files are affected by the owner and permissions of those files" https://vessel.shippingdocker.com/docs/linux-permissions/

The containers you defined are running as root, while the files created by composer belong to my host user (flayshon:flayshon). Is there something I can add to the Dockerfile to make this work without the chmod workaround?

FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream.

Hi,

I am getting this error in my docker nginx log:

2020/04/01 05:17:07 [error] 6#6: *12 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.19.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.19.0.2:9000", host: "localhost:7080"
172.19.0.1 - - [01/Apr/2020:05:17:07 +0000] "GET / HTTP/1.1" 404 27 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
172.19.0.1 - - [01/Apr/2020:05:17:07 +0000] "GET /favicon.ico HTTP/1.1" 200 0 "http://localhost:7080/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"

Log in my php container:

172.19.0.6 -  01/Apr/2020:04:25:29 +0000 "GET /index.php" 404

The only difference I made was to change to listen on my computer's 7080 port instead of the default 8080.
Basically keep getting 404 File Found when hitting the endpoint. Can someone help :) Thank you!

Compose missing extension

Hi,

Thank you for your 2 articles...
I'm wondering how would you handle such situation.
I have (like you suggest) a separate composer container.
I require in my composer.json a package that requires exif extension.

When I run docker-compose run --rm composer install it starts (all good) but stops with:

  • Your requirements could not be resolved to an installable set of packages.
  • ... requires ext-exif

Of course I can require this extension in the Dockerfile and then run the composer commands from the php container but what if I want to keep your flow? How can I make this separate composer container working? Do I have to extend and rebuild the composer image? Is there another way?

Thanks

/var/www/html/vendor does not exist and could not be created.

Hi!

I'm trying to make composer update "docker-compose run --rm composer update"
But I'm running into:
[RuntimeException]
/var/www/html/vendor does not exist and could not be created.

My laravel project is inside src folder.

Am I missing something?

imposible to install phpoffice/phpspreadsheet

Is there a way to install phpoffice/phpspreadsheet, I have try a lot of possibilities, but non of them seem to work. I always get the next message:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - phpoffice/phpspreadsheet 1.14.1 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - phpoffice/phpspreadsheet 1.14.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - Installation request for phpoffice/phpspreadsheet ^1.14 -> satisfiable by phpoffice/phpspreadsheet[1.14.0, 1.14.1].

  To enable extensions, verify that they are enabled in your .ini files:
    - /usr/local/etc/php/php-cli.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-zip.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Installation failed, reverting ./composer.json to its original content.

Any way, this is the last version php.dockerfile I end up, as you can see, it has gd installed, I'm out of ideas, Thanks for any help

FROM php:7.3-fpm-alpine

COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

WORKDIR /var/www/html

#Install imagemagick:
ENV MAGICK_HOME=/usr

RUN apk --no-cache update \
    && apk --no-cache upgrade \
    && apk add --update freetype-dev libwebp-dev libpng libpng-dev zlib-dev libxpm-dev gd \
    libjpeg-turbo-dev libxml2-dev autoconf g++ imagemagick-dev imagemagick libtool make \
    && docker-php-ext-configure gd \
        --with-gd \
        --with-freetype-dir=/usr/include/ \
        --with-png-dir=/usr/include/ \
        --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install gd \
    && docker-php-ext-install mbstring \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install opcache \
    && docker-php-ext-install soap \
    && docker-php-ext-install pdo pdo_mysql \
    && pecl install imagick \
    && docker-php-ext-enable imagick \
    && docker-php-ext-enable gd \
    && apk del autoconf g++ libtool make

How to run an artisan command from inside webpack.mix.js?

Hi, thanks a lot for this nice introduction to use docker in Laravel.

I managed to set it up, but now I am basically struggling to use an artisan command run by webpack.mix.js.

mix.copy('resources/js/Mixins/localizations.js', 'public/js/localizations.js') .js('resources/js/app.js', 'public/js/app.js') .postCss('resources/css/app.css', 'public/css', [ require('tailwindcss'), ]) .tailwind('./tailwind.config.js') .webpackConfig({ output: { chunkFilename: 'js/[name].js?id=[chunkhash]' }, resolve: { alias: { vue$: 'vue/dist/vue.runtime.esm.js', '@': path.resolve('resources/js'), }, }, plugins: [ new WebpackShellPlugin({onBuildStart:['php artisan lang:js resources/js/Mixins/localizations.js --quiet'], onBuildEnd:[]}) ] }) .babelConfig({ plugins: ['@babel/plugin-syntax-dynamic-import'], });

I just wonder how to use the onBuildStart to call the corresponding artisan container as it always throws an error like

Error: spawn php ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19) at onErrorNT (internal/child_process.js:467:16) at processTicksAndRejections (internal/process/task_queues.js:84:21) Emitted 'error' event on ChildProcess instance at: at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12) at onErrorNT (internal/child_process.js:467:16) at processTicksAndRejections (internal/process/task_queues.js:84:21) { errno: -2, code: 'ENOENT', syscall: 'spawn php', path: 'php', spawnargs: [ 'artisan', 'lang:js', 'resources/js/Mixins/localizations.js', '--quiet' ] }

Would be nice to hear from someone, who may have resolved this kind of issue.

Cheers,

Christian

Any command within npm container errors

Hello,

Thank you for your excellent template, I am however struggling to run anything within the npm container.

$ docker-compose run --rm npm version
{
npm: '6.13.6',
ares: '1.15.0',
brotli: '1.0.7',
cldr: '36.0',
icu: '65.1',
llhttp: '2.0.1',
modules: '79',
napi: '5',
nghttp2: '1.40.0',
node: '13.7.0',
openssl: '1.1.1d',
tz: '2019c',
unicode: '12.1',
uv: '1.34.1',
v8: '7.9.317.25-node.28',
zlib: '1.2.11'
}

$ docker-compose run --rm npm install

npm ERR! code Z_DATA_ERROR
npm ERR! errno -3
npm ERR! zlib: incorrect data check

$ docker-compose run --rm npm run dev
sh: 1: cross-env: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! @ development: cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-05-17T11_17_26_482Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: npm run development
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

$ docker-compose run --rm npm install cross-env
npm ERR! code EPROTO
npm ERR! syscall symlink
npm ERR! path ../which/bin/node-which
npm ERR! dest /var/www/html/node_modules/.bin/node-which
npm ERR! errno -71
npm ERR! EPROTO: protocol error, symlink '../which/bin/node-which' -> '/var/www/html/node_modules/.bin/node-which'

Slow on Mac OS

I followed your instructions both on Windows and Mac. It worked like charm on Windows but on Mac both CLI (like php artisan inspire) and site rendering time in browser are really slow. Do you think adding a ubuntu-alpine layer on top will help ?

Question: Adding an existing laravel project from github

Due to windows constantly reverting my changes to my host file, I finally decided to move away from WAMP for my laravel project.

I simply gitted my exsiting project into the /src directory.
But something seems to be a miss. Because docker-compose up -d --build site will choke on node_modules and vendor directory when I make changes that require a rebuild.

I tried .dockerignore but it did not help.

Am I suppose to maybe add my laravel git to the build image container?

Does anyone have some magic for docker-compose.yml ?

This workaround does work: #33

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.