Home > OS >  Can't load css and js files with docker
Can't load css and js files with docker

Time:08-05

I am new to docker and i ran into a problem when i call css and javascript files in php file i found that they are not loaded

Following my code: docker-compose.yml

version: '3.9'

services:
  php-env:
    build: .
    volumes:
      - ./src:/var/www/html
    ports:
      - "8080:80"
  db:
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_DATABASE: airline
      MYSQL_ROOT_PASSWORD: root

  phpmyadmin:
    image: phpmyadmin:latest
    restart: always
    ports:
      - "8081:80"
    environment:
      - PMA_ARBITRARY=1

dockerfile

FROM php:8.0-apache
WORKDIR /var/www/html
RUN apt-get update -y && apt-get install -y libmariadb-dev
RUN docker-php-ext-install pdo_mysql

my file layout is like this

-resources
--app.css
--app.js
-src
--index.php

I'm fetching the css file like this: <link rel="stylesheet" href="/resources/app.css">

The error I get when I go to the css or js file is:

Not found

The requested URL was not found on this server.

Apache/2.4.54 (Debian) Server at localhost Port 8080

CodePudding user response:

I have managed to get it working on my end, here is the application I created:

/src/index.php

<link rel="stylesheet" href="/resources/app.css">
<?php ?>
<p>Hello World</p>

/resources/app.css:

p {
    color: #FF0000
}

Here are the changes I made to the docker-compose.yml and Dockerfile to get it working:

docker-compose.yml

  1. Removed the volume binding for php-env service (since we are going to copy this in the Dockerfile)

version: '3.9'

services:
  php-env:
    build: .
    ports:
      - "8080:80"
  db:
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_DATABASE: airline
      MYSQL_ROOT_PASSWORD: root

  phpmyadmin:
    image: phpmyadmin:latest
    restart: always
    ports:
      - "8081:80"
    environment:
      - PMA_ARBITRARY=1

Dockerfile

  1. Copied the /src directory into /var/www/html
  2. Copied the /resources directory into /var/www/html/resources

FROM php:8.0-apache
WORKDIR /var/www/html
COPY ./src ./
COPY ./resources ./resources
RUN apt-get update -y && apt-get install -y libmariadb-dev
RUN docker-php-ext-install pdo_mysql

  • Related