Error failed to open apk database permission denied

Can no longer install packages #214 Comments Using alpine:latest, scripts using apk add no longer work. apk add curl — Worked on images prior to 304.0.0. Now receiving the following error: I’m guessing it’s related to this commit: 96834d0 Would be good to understand if this is intended behaviour / an intended change or […]

Содержание

  1. Can no longer install packages #214
  2. Comments
  3. Alpine Docker ОШИБКА: невозможно заблокировать базу данных: в доступе отказано ОШИБКА: не удалось открыть базу данных apk: в разрешении отказано
  4. ошибка открытия: EACCES (отказано в разрешении)
  5. 13 ответов
  6. How to Fix Exception ‘open failed: EACCES (Permission denied)’ on Android 11/12
  7. How to resolve abov error using LegacyStorage?
  8. Wrap up
  9. Исключение «Ошибка открытия: EACCES (В доступе отказано)» на Android

Can no longer install packages #214

Using alpine:latest, scripts using apk add no longer work.

apk add curl — Worked on images prior to 304.0.0.

Now receiving the following error:

I’m guessing it’s related to this commit: 96834d0

Would be good to understand if this is intended behaviour / an intended change or a regression.

The text was updated successfully, but these errors were encountered:

I think this is also related to an issue I’m seeing in cloudbuild using a build step like:

It results in an error message like:

In our case it was related to this commit and recent update to the Docker images. The containers no longer uses the root user, but a new one ( cloudsdk ).

To fix this, we needed to switch our Circle CI configuration to use root:

I have just reverted the commit. I will try testing this locally, but would also appreciate hearing if this addresses the issue for @ababkov and @patrickmcgraw .

@gerbercj Is there an ETA on when the revert will be live on gcr.io? This broke my build with the following step:

I can confirm that manually pinning our version to 303.0.0-alpine did work. But rolling it back to alpine latest just now still did not work.

The same issue with slim version,
Couldn’t install additional packages on top with apt getting error:

This broke some of our builds as well, changing the user to non-root is likely to cause problems for quite a few people.

Reverting the google/cloud-sdk image might be a good idea, at least for a day or so so we can update our systems.

In our case, a concourse task step implicitly assumed the cloud-sdk user to be root, and the change caused a difficult-to-diagnose error where writing files suddenly stopped working.

Any idea how I can make it work on cloud build? How do I run steps as root? All our builds are failing now.

@gerbercj The 9cd1269717bc revision of 304.0.0-alpine is working in our build now.

@gerbercj, I’ve observed the following, pulling from google/cloud-sdk:latest :

  • about 30 minutes ago, the sha256:dca800e43a50972e4de6e32f2cded14f1feeee2bdc9dd630d7f0514881c7657d revision made things depending on root work again
  • a subsequent update about 15 minutes ago, to sha256:4df3c4e46642e80fdb7963c4cdbb816bc6f9f2be4b71b7b29517a89d953f04e9 broke things again

Is it your intention to revert google/cloud-sdk:latest to the root user version or is the revert to the non-root version intentional?

I’ve just finished pushing updated images to Dockerhub and gcr.io. This includes updating the ‘latest’ tag to include the new commits.

@gerbercj will this change back later? I cannot find how to run a cloud build step as root. We need to install custom packages such as jq.

@gerbercj We just ran the latest tag but saw the same permission issue.

We are seeing the same issue on Cloud Build with the latest tag.

Thanks for the updates everyone. I’m looking at the updated images now to see why they would be missing the rollback. Once we sort this out the expected state is that the containers are running as root, as they were before commit 96834d0.

Источник

Alpine Docker ОШИБКА: невозможно заблокировать базу данных: в доступе отказано ОШИБКА: не удалось открыть базу данных apk: в разрешении отказано

Поэтому я использовал докер по умолчанию для testcafe, который на концентраторе докеров — testcafe / testcafe, и мне нужно запустить несколько скриптов testcafe.

Однако мне нужен снимок экрана, который запускается при ошибке, чтобы его можно было загрузить куда-нибудь, где я смогу посмотреть его позже, после того, как образ докера будет запущен.

Я использую программу Imgur, которая использует bash, поэтому я переделал несколько вещей, чтобы сделать ее совместимой с sh, и все работает, за исключением того, что мне нужен curl. Я пробовал бежать

но я получаю сообщение об ошибке

Нет, это означает, что у меня нет разрешения на это, но могу ли я обойти это, есть ли способ стать пользователем root (это в конвейере битбакета).

Я НЕ очень хочу создавать свой собственный докер.

Также обратите внимание, что все вопросы, которые я обнаружил по этому поводу, касаются установки при создании докера, однако мой вопрос в том, как это сделать после создания докера. спасибо (хороший ответ — еще один способ сохранить снимок экрана, но желательно не с помощью ssh).

Вы можете добавить команду -u = «root» при запуске контейнера: docker run -it -u = «root» testcafe / testcafe Это то, что вам нужно?

спасибо @Marion, но я спрашиваю о том, что после того, как я нахожусь в докере, не запускаю докер

@ Vladimir_314159 Вам действительно стоит попробовать предложение @ Marion, потому что указание пользователя в командной строке докера запустит команду по умолчанию или предоставленную команду в качестве этого пользователя в контейнере (следовательно, если вы запустите оболочку, вы закончите оболочку как root, который вам, вероятно, понадобится для работы с apk add ). Я столкнулся с той же проблемой, что и вы описываете, и это было решение.

я могу сделать это на конвейере битбакета? @GuillaumeG.

@ Vladimir_314159 В Bitbucket Pipelines можно использовать тег «run-as». confluence.atlassian.com/bitbucket/… Вы бы хотели работать как «0».

Для меня эта проблема была решена путем удаления контейнера и образа с помощью docker rmi . Сначала он удалил теги, после чего я удалил его и восстановил. После вытягивания он снова заработал и правильно назначил пользователей.

Если контейнер уже запущен, вы также можете указать пользователя для docker exec: docker exec -it -u=root bash , а затем сделать apk add curl

Источник

ошибка открытия: EACCES (отказано в разрешении)

у меня очень странная проблема с доступом к хранилищу на некоторых устройствах. Приложение работает на моих тестовых устройствах (Nexus 4 & 7, Samsung GS5). Все мои устройства под управлением Android 4.4.2. Но я получил много писем от пользователей, говорящих, что приложение не может писать в хранилище (ни внутреннее хранилище, ни sd-карта). Из файла журнала, полученного от отзывов пользователей, я вижу, что проблема заключается в следующем коде:

он выдает исключение в строке fStream = new FileOutputStream (filename, true); при создании FileOutputStream.

в AndroidManifest.xml у меня есть следующие объявленные разрешения:

Я подтвердил, что пользователи используют личное приложение на SD-карте. И что еще более странно, что он не может писать во внутреннюю память. Как это может произойти, если у меня есть разрешения на чтение и запись? Пользователи говорят, что они не подключают свои устройства на ПК в то время.

оказывается, я слишком часто вызываю open и close FileOutputStream, что в какой-то момент вызывает FileNotFoundException. Больше похоже на проблему с потоками.

13 ответов

я столкнулся с аналогичной проблемой некоторое время назад.

ваша проблема может быть в двух разных местах. Это либо то, как вы создаете файл для записи, либо ваш метод записи может быть ошибочным в том, что он зависит от телефона.

Если вы записываете файл в определенное место на SD-карте, попробуйте использовать переменные среды. Они всегда должны указывать на действительное местоположение. Вот пример записи в папку downloads:

Если вы запись файла во внутреннее хранилище приложения. Попробуйте следующий пример:

лично я полагаюсь на внешние библиотеки для обработки потоковой передачи в файл. Этот еще не подвел меня.

Я потерял данные слишком много раз на неудачной команде записи, поэтому я полагаюсь на известные и проверенные библиотеки для моей тяжелой работы.

Если файлы большие, вы также можете посмотреть на запуск ввода-вывода в фоновом режиме или использовать обратные вызовы.

Если вы уже используете переменные окружения, это может быть проблема с разрешениями. Ознакомьтесь с ответом Джастина Фидлера ниже.

для API 23+ вам нужно запросить разрешения на чтение/запись, даже если они уже есть в вашем манифесте.

в моем случае у меня был неправильный случай в

android.permission должно быть строчным, и каким-то образом вся строка была прописной в нашем источнике.

Я также столкнулся с той же проблемой. После тяжелой работы я понял, что в моем случае было не так. Мое устройство было подключено к компьютеру через USB-кабель. Существуют типы для USB-соединений, таких как массовое хранение, медиа-устройство(MTP), камера(PTP) и т. д. Мой тип соединения был — «массовое хранилище», и это вызывало проблемы. Когда я изменил тип соединения, проблема была решена.

всегда помните при доступе к файловой системе на устройстве android: —

НЕ ПОДКЛЮЧАЙТЕСЬ КАК МАССА Хранение на компьютере / ПК.

в моем случае это была проблема с разрешениями. Загвоздка в том, что на устройстве с Android 4.0.4 я получил доступ к файлу без каких-либо ошибок или исключений. И на устройстве с Android 5.1 это не удалось с исключением доступа (open failed: EACCES (разрешение отказано)). Обработал его с добавлением разрешения follow для манифеста файла:

поэтому я предполагаю, что это разница между управлением разрешениями в версиях ОС, которые вызывают сбои.

сначала дайте или проверьте разрешения, такие как

Если эти два разрешения в порядке, то проверьте, что выходные потоки находятся в правильном формате.

В моем случае я использовал параметр android:isolatedProcess=»true» на service на AndroidManifest.xml .

как только я удалил его, ошибка исчезла.

я столкнулся с той же проблемой и обнаружил, что мне нужно запросить разрешения во время выполнения, даже если я объявил об этом в манифесте. Так же, как и ответ Джастина Фидлера.

моя реализация немного отличается от ответа Джастина Фидлера, что он также реализует метод onrequestpermissionsresult фрагмента v4 для ручка разрешений «запрос-ответ».

У меня такая же проблема, но Иногда самый сложный вопрос получает простой ответ.

я перепроверяю разрешения манифеста, и was_not пишет разрешение позор мне.

также я нашел решение для моего пути.

перед запуском приложения я предоставил root file-explorer и не отключил разрешение на запись / чтение при выходе из приложения.

мое приложение не может использовать внешнюю память, пока я делал устройство restrat для сброса всех разрешений.

Если клиенты используют Android 6.0, Android добавил новый модель разрешение for (зефир).

трюк: если вы нацелены на версию 22 или ниже, ваше приложение запросит все разрешения во время установки, как и на любом устройстве под управлением ОС ниже Marshmallow

в моем случае проблема заключалась в конфигурации WIFI, которая была статической, имела конфликт с другим устройством, использующим тот же IP-адрес.

в моем случае я забыл добавить / перед именем файла после добавления я избавился от него

Источник

How to Fix Exception ‘open failed: EACCES (Permission denied)’ on Android 11/12

Today, I was working with my old program, which I had made in December 2020. Due to some odd reason, I delayed my app development process.

An application was working a few months back suddenly the app gets crashed with the error Exception ‘open failed: EACCES (Permission denied)’

The application workflow was pretty simple. When the user clicks on Share Button programmatically, the application will take a screenshot and use the explicit intent to send screenshots using any applications that support Image share.

I took a paused for a moment and started thinking, What wrong suddenly happen to the project? If you read the error, it says something is wrong with the permissions.

Instantly I checked with the permissions code found everything good when I open Android Manifest found the culprit “WRITE_EXTERNAL_STORAGE no longer provides write access when targeting Android 10+.”

The problem starts getting clear. I open build.gradle and checked target version is changed to API 30 (Android 11) somehow.

As usual, I did research and found that the Application target for SDK 29 or later uses scoped storage as the default option.

If you are thinking, What is Scoped Storage? I’ll clarify to you that Scoped Storage sets a limit to the access file.

For example, If my XYZ application is stored in a specific directory location, want to upload photos from any other Directory other than the application directory, I’ll not be allowed to access the file according to the new google policy.

So we got the problem; tell me, Gagan, how to resolve this? You can use the MediaStore method or simply use the Legacy Storage policy.

How to resolve abov error using LegacyStorage?

We need to pass the single line of code, which will turn off the flag for Android 10+ devices, and you will be allowed to use LegacyStorage.

Go to the project pane and Click on AndroidManifest and add the highlighted code inside .

Changes should be like this below Sample Image.

Once you add the requestLegacyExternalStorage = “true” under the tag. That’s all for android 10 or 11 users you can test your application.

For android 12 users need to add one more tag in AndroidManifest.xml that is “android:exported=”true” for the MainActivity.

Run the application and your application functions will start working again.

Wrap up

That’s it to resolve Exception ‘open failed: EACCES (Permission denied)’. If you are still facing any issues while following this guide, please let us know in the comment section.

For your ease, we have uploaded a sample project to the GitHub repository. To clone the repository click on this link.

What are your thoughts about this article?

A man with a tech effusive who has explored some of the amazing technology stuff and is exploring more. While moving towards, I had a chance to work on Android development, Linux, AWS, and DevOps with several open-source tools.

Источник

Исключение «Ошибка открытия: EACCES (В доступе отказано)» на Android

открыть не удалось: EACCES (Permission denied)

на линии OutputStream myOutput = new FileOutputStream(outFileName);

Я проверил рут и попробовал android.permission.WRITE_EXTERNAL_STORAGE .

Как я могу решить эту проблему?

У меня была такая же проблема . Это было не в том месте. Это правильно:

uses-permission Тег должен быть вне application тега.

Для API 23+ вам необходимо запросить разрешения на чтение / запись, даже если они уже есть в вашем манифесте.

У Google появилась новая функция на Android Q : отфильтрованное представление для внешнего хранилища. Быстрое решение проблемы — добавить этот код в файл AndroidManifest.xml:

Я наблюдал это один раз при запуске приложения внутри эмулятора. В настройках эмулятора необходимо правильно указать размер внешнего хранилища («SD-карта»). По умолчанию поле «внешнее хранилище» пустое, и это, вероятно, означает, что такого устройства нет, и EACCES выбрасывается, даже если в манифесте предоставляются разрешения.

В дополнение ко всем ответам, убедитесь, что вы не используете свой телефон в качестве USB-накопителя.

У меня была такая же проблема в HTC Sensation при включенном режиме USB-накопителя. Я все еще могу отлаживать / запускать приложение, но не могу сохранить на внешнее хранилище.

Добавить андроида: requestLegacyExternalStorage = «истина» в Android Manifest Он работал с Android 10 (Q) в SDK 29+
или После перенастройки Android X .

Моя проблема была с «TargetApi (23)», которая необходима, если ваш minSdkVersion ниже 23.

Итак, у меня есть запрос на разрешение со следующим фрагментом

Решение для Android Q :

Я испытываю то же самое. Я обнаружил, что если вы идете в Настройки -> Диспетчер приложений -> Ваше приложение -> Разрешения -> Включить хранилище , это решает проблему.

Оказалось, это была глупая ошибка, так как мой телефон все еще был подключен к настольному ПК и я не осознавал этого.

Поэтому пришлось отключить USB-соединение, и все работало нормально.

У меня была такая же проблема на Samsung Galaxy Note 3, под управлением CM 12.1. Проблема для меня заключалась в том, что у меня было

и должен был использовать это, чтобы взять и сохранить пользовательские фотографии. Когда я попытался загрузить те же самые фотографии в ImageLoader, я получил (Permission denied) ошибку. Решение было явно добавить

так как вышеупомянутое разрешение ограничивает только разрешение на запись до API версии 18, а вместе с ним разрешение на чтение

В дополнение ко всем ответам, если клиенты используют Android 6.0, Android добавил новую модель разрешений для (Marshmallow).

Уловка: если вы нацелены на версию 22 или ниже, ваше приложение будет запрашивать все разрешения во время установки так же, как и на любом устройстве, работающем под ОС ниже Marshmallow. Если вы пытаетесь использовать эмулятор, то начиная с Android 6.0 и далее вам нужно явно перейти в настройки-> приложения-> YOURAPP -> разрешения и изменить разрешение, если вы его дали.

Странно после косой черты «/» перед моим новым файлом моя проблема была решена. Я изменил это:

У меня была такая же проблема, и ни одно из предложений не помогло. Но я нашел интересную причину для этого на физическом устройстве Galaxy Tab .

Когда USB-накопитель включен, разрешения на чтение и запись на внешнее хранилище не влияют. Просто отключите USB-накопитель, и с правильными разрешениями проблема будет решена.

Я ожидаю, что все ниже /data будет принадлежать «внутреннему хранилищу». Однако вы должны иметь возможность написать /sdcard .

Измените свойство разрешения в вашей /system/etc/permission/platform.xml
и группе необходимо упомянуть, как показано ниже.

У меня была такая же ошибка, когда я пытался записать изображение в папку DCIM / камера на Galaxy S5 (Android 6.0.1), и я понял, что только эта папка ограничена. Я просто мог написать в DCIM / любую папку, но не в камере. Это должно быть ограничение / настройка на основе бренда.

Когда ваше приложение относится к системному приложению, оно не может получить доступ к SD-карте.

имейте в виду, что даже если вы установили все правильные разрешения в манифесте: единственное место, в которое сторонним приложениям разрешено писать на вашу внешнюю карту, это «их собственные каталоги» (т.е. / sdcard / Android / data /), пытающиеся записать в в другом месте: вы получите исключение: EACCES (В доступе отказано)

Может быть, ответ таков:

на устройствах API> = 23, если вы устанавливаете приложение (приложение не является системным приложением), вы должны проверить разрешение на хранение в разделе «Настройки — приложения», для каждого приложения есть список разрешений, вы должны проверить его! пытаться

В моем случае я использовал библиотеку выбора файлов, которая возвращала путь к внешнему хранилищу, но он начинался с /root/ . И даже с разрешением WRITE_EXTERNAL_STORAGE, предоставленным во время выполнения, я все равно получил ошибку EACCES (разрешение отклонено) .
Так что используйте, Environment.getExternalStorageDirectory() чтобы получить правильный путь к внешнему хранилищу.

Пример:
не могу написать: /root/storage/emulated/0/newfile.txt
могу написать: /storage/emulated/0/newfile.txt

При использовании этого устаревшего метода с Android 29 и далее вы получите ту же ошибку:

java.io.FileNotFoundException: open failed: EACCES (Permission denied)

Для тех, кто приходит сюда из результатов поиска и ориентируется на Android 10: Android 10 (API 29) меняет некоторые разрешения, связанные с хранением.

Я исправил эту проблему, когда заменил свои предыдущие экземпляры Environment.getExternalStorageDirectory() (что устарело в API 29) на context.getExternalFilesDir(null) .

Обратите внимание, что context.getExternalFilesDir(type) может возвращать ноль, если место хранения недоступно, поэтому обязательно проверяйте это всякий раз, когда проверяете, есть ли у вас внешние разрешения.

Я создаю папку в / data / в моем init.rc (возиться с aosp на Nexus 7) и имел именно эту проблему.

Оказалось, что предоставления разрешения для папки rw (666) было недостаточно, и это должно было быть rwx (777), тогда все работало!

Применение разрешений на хранение после 6.0 можно обойти, если у вас есть рутированное устройство с помощью этих команд adb:

Источник

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

ababkov opened this issue

Aug 4, 2020

· 19 comments


Closed

Can no longer install packages

#214

ababkov opened this issue

Aug 4, 2020

· 19 comments

Comments

@ababkov

Using alpine:latest, scripts using apk add no longer work.

apk add curl — Worked on images prior to 304.0.0.

Now receiving the following error:

ERROR: Unable to lock database: Permission denied
ERROR: Failed to open apk database: Permission denied

I’m guessing it’s related to this commit: 96834d0

Would be good to understand if this is intended behaviour / an intended change or a regression.

@patrickmcgraw

I think this is also related to an issue I’m seeing in cloudbuild using a build step like:

- name: gcr.io/google.com/cloudsdktool/cloud-sdk:alpine
  entrypoint: gcloud
  id: configured
  args:
  - 'config'
  - 'set'
  - 'app/cloud_build_timeout'
  - '3000s'

It results in an error message like:

BUILD
Starting Step #0 - "configured"
Step #0 - "configured": Pulling image: gcr.io/google.com/cloudsdktool/cloud-sdk:alpine
Step #0 - "configured": alpine: Pulling from google.com/cloudsdktool/cloud-sdk
Step #0 - "configured": cbdbe7a5bc2a: Already exists
Step #0 - "configured": 6e00981b9060: Pulling fs layer
Step #0 - "configured": 1b42e8b6fcb3: Pulling fs layer
Step #0 - "configured": 995add225b99: Pulling fs layer
Step #0 - "configured": 2dadf6e2c33a: Pulling fs layer
Step #0 - "configured": 2dadf6e2c33a: Waiting
Step #0 - "configured": 1b42e8b6fcb3: Verifying Checksum
Step #0 - "configured": 1b42e8b6fcb3: Download complete
Step #0 - "configured": 2dadf6e2c33a: Verifying Checksum
Step #0 - "configured": 2dadf6e2c33a: Download complete
Step #0 - "configured": 6e00981b9060: Verifying Checksum
Step #0 - "configured": 6e00981b9060: Download complete
Step #0 - "configured": 995add225b99: Verifying Checksum
Step #0 - "configured": 995add225b99: Download complete
Step #0 - "configured": 6e00981b9060: Pull complete
Step #0 - "configured": 1b42e8b6fcb3: Pull complete
Step #0 - "configured": 995add225b99: Pull complete
Step #0 - "configured": 2dadf6e2c33a: Pull complete
Step #0 - "configured": Digest: sha256:a53293944e9ace21f3b0d7c22e5e6b41b41016b154e9632e218e5407cb43150f
Step #0 - "configured": Status: Downloaded newer image for gcr.io/google.com/cloudsdktool/cloud-sdk:alpine
Step #0 - "configured": gcr.io/google.com/cloudsdktool/cloud-sdk:alpine
Step #0 - "configured": WARNING: Could not setup log file in /builder/home/.config/gcloud/logs, (Error: Could not create     directory [/builder/home/.config/gcloud/logs/2020.08.04]: Permission denied.
Step #0 - "configured": 
Step #0 - "configured": Please verify that you have permissions to write to the parent directory.)
Step #0 - "configured": ERROR: (gcloud.config.set) Failed to create the default configuration. Ensure your have the correct     permissions on: [/builder/home/.config/gcloud/configurations].
Step #0 - "configured":   Could not create directory [/builder/home/.config/gcloud/configurations]: Permission denied.
Step #0 - "configured": 
Step #0 - "configured": Please verify that you have permissions to write to the parent directory.

@baublet

In our case it was related to this commit and recent update to the Docker images. The containers no longer uses the root user, but a new one (cloudsdk).

To fix this, we needed to switch our Circle CI configuration to use root:

  build-docker:
    docker:
      - image: google/cloud-sdk
        user: root   # <-- This is new, and fixed the image

YMMV

@gerbercj

I have just reverted the commit. I will try testing this locally, but would also appreciate hearing if this addresses the issue for @ababkov and @patrickmcgraw .

@allanlw

@gerbercj Is there an ETA on when the revert will be live on gcr.io? This broke my build with the following step:

- name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
  entrypoint: gcloud
  args: ["app", "deploy", "app.yaml", "cron.yaml", "-v", "prod", "--stop-previous-version", "--promote"]

@patrickmcgraw

@gzeskas

The same issue with slim version,
Couldn’t install additional packages on top with apt getting error:

Step 1/3 : FROM google/cloud-sdk:slim
 ---> 6f2ad1762d73
Step 2/3 : RUN apt-get update && apt-get install -y bash
 ---> Running in 1708bfe0d002
Reading package lists...
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/

@miguelsimon

This broke some of our builds as well, changing the user to non-root is likely to cause problems for quite a few people.

Reverting the google/cloud-sdk image might be a good idea, at least for a day or so so we can update our systems.

In our case, a concourse task step implicitly assumed the cloud-sdk user to be root, and the change caused a difficult-to-diagnose error where writing files suddenly stopped working.

@thecodeassassin

Any idea how I can make it work on cloud build? How do I run steps as root? All our builds are failing now.

@patrickmcgraw

@gerbercj The 9cd1269717bc revision of 304.0.0-alpine is working in our build now.

@miguelsimon

@gerbercj, I’ve observed the following, pulling from google/cloud-sdk:latest:

  • about 30 minutes ago, the sha256:dca800e43a50972e4de6e32f2cded14f1feeee2bdc9dd630d7f0514881c7657d revision made things depending on root work again
  • a subsequent update about 15 minutes ago, to sha256:4df3c4e46642e80fdb7963c4cdbb816bc6f9f2be4b71b7b29517a89d953f04e9 broke things again

Is it your intention to revert google/cloud-sdk:latest to the root user version or is the revert to the non-root version intentional?

@gerbercj

I’ve just finished pushing updated images to Dockerhub and gcr.io. This includes updating the ‘latest’ tag to include the new commits.

@thecodeassassin

@gerbercj will this change back later? I cannot find how to run a cloud build step as root. We need to install custom packages such as jq.

@alexrohv

@sww314

We are seeing the same issue on Cloud Build with the latest tag.

Digest: sha256:4df3c4e46642e80fdb7963c4cdbb816bc6f9f2be4b71b7b29517a89d953f04e9
Status: Downloaded newer image for gcr.io/google.com/cloudsdktool/cloud-sdk:latest
gcr.io/google.com/cloudsdktool/cloud-sdk:latest

@gerbercj

Thanks for the updates everyone. I’m looking at the updated images now to see why they would be missing the rollback. Once we sort this out the expected state is that the containers are running as root, as they were before commit 96834d0.

@gerbercj

I’ve just finished running our standard Cloud Build pipeline to regenerate the gcr.io images in the same manner as a standard deployment process. I then pulled the each container and ran whoami in it, all of which returned root.

@miguelsimon

Seeing the expected behaviour on the dockerhub google/cloud-sdk:latest image revision 72ce62fcbefb, thanks @gerbercj.

@loozhengyuan

Sorry everyone for inconvenience today, this was on me, should have tested it more extensively before submitting the change. Glad that it was reverted quickly, thanks @gerbercj.

@ababkov

Thanks all for participating and @gerbercj for actioning the fix ❤️ Can confirm issue the issue posted is resolved.

Alpine Linux — это минималистичный Docker-образ на базе имеет размер всего 5 МБ, но многие обычные для Linux утилиты в нем, по умолчанию, не установлены. Рассмотрим как из командной строки установить пакет в Alpine-контейнере с помощью apk (менеджера пакетов Alpine).

Установка Пакетов в Alpine


# apk update  --- обновление всех пакетов
# apk add  --- установка пакета

Также пакет в Alpine может быть установлен с использованием опции —no-cache:

# apk --no-cache add 

Она позволяет устанавливать пакеты с обновленным индексом «на лету», т.е. без локального кэша.

Если возникают ошибки вида: ERROR: Unable to lock database: Permission denied или ERROR: Failed to open apk database: Permission denied , то просто подключитесь к Docker-контейнеру как root.

Чтобы установить пакет в Docker-образе на базе Alpine, добавьте следующую строку в Dockerfile:

RUN apk --no-cache add 

Если надо найти определенный пакет, то используйте команду:

 apk search 

A minimal Docker image based on Alpine Linux has only 5 MB in size, but a lot of packages common for Linux distributions are not installed by default.

In this short note i will show how to install a package in Alpine container from the command line using the apk (Alpine package manager).

I will also show how to build an Alpine-based Docker image with additionally installed packages.

Cool Tip: Enter a running Docker container and start a bash session! Read More →

Update the Alpine repository indexes:

# apk update

In case of the following errors, connect to the Docker container as root:

ERROR: Unable to lock database: Permission denied
ERROR: Failed to open apk database: Permission denied

Search for a package to install on Alpine:

# apk search <package>
- or -
# apk search -a <package>
Option Description
-a, --all Show all package versions (instead of the latest only)

Install a package on Alpine Linux from the command line:

# apk add <package>
- example -
# apk add curl

The package on Alpine can also be installed using the --no-cache option:

# apk --no-cache add <package>

Alpine Linux 3.3 and heigher: The --no-cache option has been added in Alpine Linux 3.3. It allows to install packages with an index that is updated and used on-the-fly and not cached locally.

To install a package in Alpine-based Docker image, add the following line to a Dockerfile:

RUN apk --no-cache add <package>

On the older versions of Alpine, a package can be installed as follows:

RUN apk add --update <package> && 
    rm -rf /var/cache/apk/*

Cool Tip: Clean up a Docker host! Remove unused Docker containers! Read More →

Поэтому я использовал докер по умолчанию для testcafe, который на концентраторе докеров — testcafe / testcafe, и мне нужно запустить несколько скриптов testcafe.

Однако мне нужен снимок экрана, который запускается при ошибке, чтобы его можно было загрузить куда-нибудь, где я смогу посмотреть его позже, после того, как образ докера будет запущен.

Я использую программу Imgur, которая использует bash, поэтому я переделал несколько вещей, чтобы сделать ее совместимой с sh, и все работает, за исключением того, что мне нужен curl. Я пробовал бежать

apk add curl

Но я получаю сообщение об ошибке

ERROR: Unable to lock database: Permission denied ERROR: Failed to open apk database: 

Нет, это означает, что у меня нет разрешения на это, но могу ли я обойти это, есть ли способ стать пользователем root (это в конвейере битбакета).

Я НЕ очень хочу создавать свой собственный докер.

Также обратите внимание, что все вопросы, которые я обнаружил по этому поводу, касаются установки при создании докера, однако мой вопрос в том, как это сделать после создания докера. спасибо (хороший ответ — еще один способ сохранить снимок экрана, но желательно не с помощью ssh).

1. Overview

Alpine Linux is a lightweight Linux distribution that has become popular for building Docker images. It incorporates the Busybox Linux core utilities and the Musl Libc C standard library implementation. Docker images created with Alpine Linux have a small memory footprint compared to those created with the majority of other Linux distributions.

The root user is the default user in the official Alpine Linux Docker image. This tutorial will examine how we can create other user accounts for our image and use them by default.

2. The Dockerfile

The Dockerfile USER command sets the default user account and group during the image build phase. The account specified will be used in all subsequent RUN commands. The account has to be created in the Dockerfile or it has to pre-exist in the Alpine Docker image:

FROM alpine:latest
RUN adduser -D baeldung
USER baeldung

Here, we create the user account baeldung with the adduser command. Moreover, by using the -D option, the user is created without a password. The USER command sets the current user to baeldung.

Next, we build an image and run a new container to test our Dockerfile:

$ sudo docker image build -q -t baeldung-alpine .
sha256:3012e46b9fbcd50c5c9799e7cf8fb617cfa8ee54f1d152614a2f4d6e6e04ee7b
$ sudo docker container run --rm -it baeldung-alpine
/ $ whoami
baeldung

Indeed, the logged-on user is baeldung. Note that the Alpine distribution doesn’t have the useradd command.

3. Setting a Password

To set a password in the Dockerfile, we use the chpasswd command:

FROM alpine
RUN adduser baeldung;echo 'baeldung:123' | chpasswd
USER baeldung

As can be seen, we use the pipe operator to send input to the chpasswd command. The chpasswd command accepts string input in the user:password format.

4. Dealing With Permissions

Until now, we’ve created a new user and set a password. We should note, however, that our user has limited privileges. We can verify this if we try to install a package with the apk command:

$ apk add apache2
ERROR: Unable to lock database: Permission denied
ERROR: Failed to open apk database: Permission denied

Indeed, our user lacks the required permissions to install new packages. Moreover, if we try to use the sudo command to run commands as root, we’ll find out that it’s missing from the official Alpine image.

To overcome missing permissions, we can install the sudo package and permit our user to run the sudo command.

However, since the motivation for using the Alpine Docker image is the low memory footprint, we may want to use the doas package instead. The doas package is a lightweight alternative to the sudo package. Let’s modify our Dockerfile to install the doas package:

FROM alpine
RUN     apk add doas; 
        adduser baeldung; 
        echo 'baeldung:123' | chpasswd; 
        echo 'permit baeldung as root' > /etc/doas.d/doas.conf
USER baeldung

Here, we do most of the work in the RUN command:

  1. Install the doas package with the apk command
  2. Create the baeldung user with the adduser command
  3. Set a password with the chpasswd command
  4. Create the /etc/doas.d/doas.conf file
  5. Use doas.conf to permit the baeldung user to run commands as root with the doas command

As a result, the container will start with the baeldung user.

5. Add User to Group

Instead of permitting our user to run commands as root, we should add our user to the wheel group. The wheel group is equivalent to the sudo group in Debian-like systems for permitting a user to run commands as root.

The doas command, however, isn’t configured to grant root permissions to the members of the wheel group by default. To allow this, we have to configure it the doas.conf file. Let’s modify our Dockerfile once more:

FROM alpine
RUN     apk add doas; 
        adduser baeldung -G wheel; 
        echo 'baeldung:123' | chpasswd; 
        echo 'permit :wheel as root' > /etc/doas.d/doas.conf
USER baeldung

Here, the adduser command creates the user baeldung as before, but now, it adds the user to the wheel group.

Moreover, we configure the doas.conf file to permit the wheel group to run commands as root. Note here that we’ve placed a colon character in front of the group name.

To verify that the user can run commands as root, let’s build and run our image:

$ sudo docker image build -qt baeldung-alpine .
sha256:d1d9c7d578f3823d75e6d35209cb60320d19ae56ea92acc54fc9b85a98a02521
$ sudo docker container run --rm -it baeldung-alpine
/ $ whoami
baeldung
/ $ doas ls -all /root
doas ([email protected]) password:
total 8
drwx------ 2 root root 4096 Aug 9 08:47 .
drwxr-xr-x 1 root root 4096 Sep 17 13:01 ..

As we can see, after building the image, we create a new container. In the container, we first check the user that is running the shell. As expected, it’s the baeldung user.

Then, we try to access the /root folder with the help of the doas command. After entering our password, we can list the contents of the /root folder.

6. Other Options

Apart from adding a user to a group and setting the user’s password, there are a few more interesting options in the adduser command and the doas command configuration.

6.1. Creating a System User

A system user can be used for running background services. System users have a different range of user IDs and may not be present on a login screen. We can create a system user with the adduser command:

$ adduser -S baeldung

Here, we used the -S option to create a system user. In addition, the –system option has the same effect.

6.2. Disable doas Password

Although this may pose security risks, we can configure the doas command so that it doesn’t ask for a password when a user wants to execute a command as root. This is configured in the /etc/doas.d/doas.conf file:

$ echo 'permit nopass :wheel as root' >> /etc/doas.d/doas.conf

6.3. Persistent Password

Another option of the doas command configuration is to make the password persistent. In other words, if the user enters their password once, then the doas command won’t ask for it over and over in subsequent executions:

$ echo 'permit persist :wheel as root' >> /etc/doas.d/doas.conf

As a result, the doas command won’t ask for a password every time. Note that for added security, the password will persist only for a limited amount of time.

7. Creating a User With Entrypoint Script

In the previous sections, we saw how we can create a user as part of our image definition. Another option is to create an ENTRYPOINT script and create the user in that script. Docker will execute the ENTRYPOINT script upon container start. Let’s create a sample script and save it to the file entrypoint.sh:

#!/bin/sh
apk add doas
adduser baeldung -D -G wheel
echo 'baeldung:123' | chpasswd
echo 'permit :wheel as root' > /etc/doas.d/doas.conf
su baeldung

The above script is similar to the shell commands we entered in the Dockerfile examples of the previous sections. So, to recap:

  • Install the doas package
  • Create the baeldung user
  • Add the baeldung user to the wheel group
  • Set a password for the baeldung user
  • Configure the wheel group in the doas configuration
  • Switch from root to the baeldung user

Next, we edit our Dockerfile so that it uses the entrypoint.sh script:

FROM alpine:latest
COPY entrypoint.sh /root/entrypoint.sh
ENTRYPOINT /root/entrypoint.sh

An important note is that we should grant the execute privilege to entrypoint.sh, otherwise our container will fail to execute it.

Now, let’s build and run our container and verify that the user is created:

$ sudo docker container run --rm -it baeldung-alpine:latest
...
/ $ whoami
baeldung
/ $ groups
wheel

Indeed, after running, we are currently logged in with the baeldung user. Then, we use the groups command to verify that our user belongs to the wheel group.

8. Conclusion

In this article, we examined how we can create a new user in an Alpine Linux Docker container and permit the user to run commands as an administrator. Finally, we looked at some interesting options for the corresponding commands.

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Изменить: Ответ настолько ясен. При входе в контейнер можно использовать флаг --user root.

docker exec -it --user root mycontainername bash                 or sh

Я только что загрузил образ 1.5.0-alpine этого официального центра докеров для службы (Kong API Gateway), и теперь я не могу запускать команды apk, например, для установки nano.

Раньше мне просто нужно было зайти в контейнер

docker exec -it kong sh 

or

docker-compose exec kong sh

и, например, я мог запускать такие команды, как apk update или apk add nano.

Но теперь я получаю эти ошибки

$ apk update                                                                                                                                   
ERROR: Unable to lock database: Permission denied                                                                                                
ERROR: Failed to open apk database: Permission denied

$ apk add nano
ERROR: Unable to lock database: Permission denied
ERROR: Failed to open apk database: Permission denied

Я также пытался запустить sudo и su … но у меня получилось

$ su
su: must be suid to work properly
$ su root
su: must be suid to work properly
$ suid
sh: suid: not found

Мне действительно нужно будет создавать свой собственный образ? Я использовал официальный, и он работал нормально.

Понравилась статья? Поделить с друзьями:
  • Error failed to mount dev loop0
  • Error failed to lookup view error in views directory
  • Error failed to load xbe file
  • Error failed to load the game dll whgame
  • Error failed to load steam api64 dll death stranding