The story of Job's sufferings is interesting because it begins in heaven with the Lord drawing Satan's attention to Job. Satan immediately slandered both Job and God by suggesting that God had bribed Job to be faithful to Him by giving him so many riches so the Lord allowed Satan to take them all away. This whole thing was repeated with the result that the Lord allowed Satan to afflict Job with a very painful illness. It seems like things would have been OK for Job if the Lord had not boasted of his faithfulness to Satan.
So why does God allow his people to suffer even sometimes allowing Satan to attack them specifically? Neither Job nor his friends could find an answer. They all thought that God would be happy with them if they were good and would punish them if they were bad. When calamity came upon Job his friends thought he must have been bad. But Job didn't think he had been so bad that he deserved what was happening to him. They couldn't figure it out. Even the conclusion of the book only gives a hint what the answer might be.
The real answer isn't made clear until you come to the epistles of Paul in the New Testament. In Ephesians he speaks of God's eternal purpose and of the mystery of God's will. The basic element of this is that God wants man to receive Him as life. He wants to grow in man and build all those who have his life into a corporate body to express Him. The starting point for this is a personal relationship with Him, not an outward trying to do good to please Him. While Job was doing his best to try to please God by doing what was good, God allowed Satan to frustrate all of that. In the end Job had a small measure of personal revelation and experience of God. That was much more satisfying to both him and God than everything Job had tried to do previously.