2

I am trying to upload images files to a folder (/public/temp_upload) under the server root. The server was written by Node.js and uploading files are done by multer. It works fine on local but when the server is moved to a docker container, it throws a permission error.

Here is the code snippet. The error occurs in put endpoint.

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, process.env.NODE_ENV === 'production' ? '/usr/src/app/public/temp_upload' : 'public/temp_upload');
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + '-' + file.originalname);
    },
});

const imageFilter = function(req, file, cb) {
    // accept image only
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
};

const upload = multer({storage: storage, fileFilter: imageFilter});

module.exports = app => {
    app.post('/', async (req, res) => {
        const key = nanoid();
        console.log(req.body.type);
        const fileType = req.body.type.replace('image/', '');
        res.json({
            key,
            url:
                process.env.NODE_ENV === 'production'
                    ? `/usr/src/app/public/upload/${req.user.id}_${key}.${fileType}`
                    : `public/upload/${req.user.id}_${key}.${fileType}`,
        }).end();
    });

    app.put('/', upload.single('image'), async (req, res) => {
        res.status(200).json({tempPath: req.file.path});
    });
};

The error is

 image/jpeg
app_1    | [Error: EACCES: permission denied, open '/usr/src/app/public/temp_upload/1584467058084-3DkRrcPOfnF4pnEWRWyRu.jpg'] {
app_1    |   errno: -13,
app_1    |   code: 'EACCES',
app_1    |   syscall: 'open',
app_1    |   path: '/usr/src/app/public/temp_upload/1584467058084-3DkRrcPOfnF4pnEWRWyRu.jpg',
app_1    |   storageErrors: []
app_1    | }``
Dream High
  • 123
  • 1
  • 10
  • create the directory in the docker and give permission to user https://stackoverflow.com/questions/45553074/cannot-create-directory-permission-denied-inside-docker-container – MonteCristo Mar 18 '20 at 01:17

1 Answers1

2

I just used volumes to solve problems. To get the better understanding of volumes, please read this section of doc. https://docs.docker.com/storage/volumes/

Here is the snippet of docker-compose.yml.

version: '3'
services:
    app:
        build:
            context: .
            args:
                - NODE_ENV=production
        command: bash -c "node setup.js && npx nodemon server.js"
        volumes:
            - ./public/temp_upload:/usr/src/app/public/temp_upload
            - ./public/upload:/usr/src/app/public/upload
        depends_on:
            - mysql
            - redis
        ports:
            - 3000:3000
...
Dream High
  • 123
  • 1
  • 10